How to create an arraylist class that can store multiple data type objects in java

StackOverflow https://stackoverflow.com/questions/23395263

  •  12-07-2023
  •  | 
  •  

문제

I am using a JDBC query that returns output as following:

Name       Id
A          1
B          2

Then I am trying to generate an arrylist based on the query result using the following java class:

private class GetCompanyInfo implements Work {
    ArrayList<CompanyRelatedInfo> companyRelatedDataList = new ArrayList<CompanyRelatedInfo>();
    private String queryString;

    @Override
    public void execute(Connection connection) throws SQLException {        
        PreparedStatement ps = connection.prepareStatement(queryString);
        ResultSet rs = ps.executeQuery();
        CompanyRelatedInfo ci = new CompanyRelatedInfo();       
        while(rs.next())
        {   
            String name = rs.getString("name");
            Long id = rs.getLong("id");

            ci.setName(name);
            ci.setId(id);
            companyRelatedDataList.add(ci);
        }   
        rs.close();
        ps.close();
    }
}

But the problem is the arraylist returns results as following:

Name       Id
B          2
B          2

How can I generate the arraylist as following:

Name       Id
A          1
B          2
도움이 되었습니까?

해결책

Create a new instance of CompanyRelatedInfo instead of using the same. You are just modifying one and the same object for all rows and put it multiple times into the list. So try and use the following:

while(rs.next()) {   
  CompanyRelatedInfo ci = new CompanyRelatedInfo();       
  ...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top