Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList storing only last table record

 
Savannah David
Greenhorn
Posts: 16
Eclipse IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Everyone ,

I have a problem in this code.I am storing table record in "arrayList" and passing it to another servlet. But the problem is , arraylist is producing only one record multiple times. If table has 3 records, then this arraylist showing only last record 3 times. Please help to get full table record in the arrayList. Many Thanks

try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String projectName = rs.getString("projectname");
String projectCode = rs.getString("projectcode");
projectVO.setProjectName(projectName);
projectVO.setProjectCode(projectCode);
arrayList.add(projectVO);

}
} catch (Exception e ) {
e.printStackTrace();
}
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It appears that you don't create a new instance of your DTO class you're using for storing the record for each row in the resultset. So in all probability your list contains N references to the same instance (a List collection allows that). The projectName and projectCode fields of the projectVO instance are overwritten with each pass of the loop, and when the loop finishes, it keeps the last value that was encountered in the loop.

You should create a new instance in the loop. Add a projectVO = new TheDTOClassName(); line into the loop before setting its values.

(Please UseCodeTags the next time. It makes your code much easier to read.)
 
Savannah David
Greenhorn
Posts: 16
Eclipse IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Martin. It really worked . I will definitely use "UseCodeTags" in my further posts. Thanks once again for the valuable suggestion.
 
Savannah David
Greenhorn
Posts: 16
Eclipse IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
-
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic