0

I was having the an issue while writing this code and I solved it, but I'm not sure about the reason behind it, so it would be great if someone would explain why it happens.

The problem is the following:

rowData is an ArrayList<String>, and reportData is an ArrayList<ArrayList>

The code below loops through results from a database, for every row of the query result, rowData is appended with the String values of the columns (The for loop) to form a complete row of data, then each row is appended to reportData.

while(rs.next()) {
    rowData.clear();
    for(int i = 0; i < wrapper.getColumnCount(); i++) {
        rowData.add(rs.getString(i+1));
    }
    System.out.println("rowData being pushed to reportData" + rowData);
    reportData.add(rowData);
}
System.out.println(reportData);

Now here's the problem: Let's suppose there are 3 rows of data. The first System.out.println prints each different row of data correctly. However, when the second one prints, it shows that the reportData is filled with the last row of data 3 times.

This is solved when I do this:

while(rs.next()) {
    //rowData.clear();
    ArrayList<String> rowData = new ArrayList<String>();
    for(int i = 0; i < wrapper.getColumnCount(); i++) {
        rowData.add(rs.getString(i+1));
    }
    System.out.println("rowData being pushed to reportData" + rowData);
    reportData.add(rowData);
}
System.out.println(reportData);

Now the reportData is filled correctly. This worked by intuition, but I am not sure exactly why this happens.

braX
  • 11,506
  • 5
  • 20
  • 33
zeind
  • 31
  • 3

0 Answers0