ArrayList of String Arrays keeps only the last entry
I need help with my ArrayList in Java. I've been debugging for a long time, but still. The problem is that I am saving some data from the database to a string array and storing that array in an ArrayList, in the output it only saves the last element multiple times. It looks like he's just rewriting it.
String[] result=new String[2];
String userId=Personal_Organizer.userProfile.getUserID();
ArrayList<Object> params = new ArrayList<Object>();
params.add(userId);
String query1 = "select * from tblMemos where "
+ "_user_id = ?";
int rows;
System.out.println(query1);
executeQueryP(query1, params);
ArrayList<String[]> fetched = new ArrayList<String[]>();
int i=0;
try {
while(rs.next()) {
result[0] = rs.getString(2);
result[1] = rs.getString(3);
System.out.print("Counter: "+i);
try{
fetched.add(i,result);//here tried just .add(result) and output is same.
i++;
}catch(Exception e){
System.out.println("Exceptional exception "+e);
}
}
// Just to check. I have 2 records in DB and it shows last record twice
System.out.println(fetched.size());
System.out.println(fetched.get(0)[0]);
System.out.println(fetched.get(1)[0]);
}
// ...
+3
source to share
1 answer
You have to create a new instance of the array on each iteration:
while(rs.next()) {
result = new String[2];
result[0] = rs.getString(2);
result[1] = rs.getString(3);
fetched.add(result);
}
Otherwise, you add the same array instance multiple times to the list, and each iteration overwrites the contents of that array with the latest data.
+5
source to share