there are only 3 sets of data in turn1.length,when temp added,there should have three different sets of data.But,after i add,even there is 3 group objects,the date in it upexpectedly is the last group of date,all.
I see three different data in debug mode,current attribute will cover the prev data in temp each cycle.
how can i fix it?
String[] turn1 = idList.split(",");
String[] turn2 = labelList.split(",");
Attribute attribute = new Attribute();
List<Attribute> Temp = new ArrayList<Attribute>();
for(int i=0;i<turn1.length;i++){
long getId;
getId = Integer.parseInt(turn1[i]);
attribute.setId(getId);
attribute.setLabel(turn2[i]);
Temp.add(attribute);
}
for(int i=0;i<3;i++)
System.out.println(Temp.get(i));
You are changing the same object in the loop, when you add an object to list, this won’t copy the object, just reference that object, so every element in the list will be pointed to the same original object.
What you should do is new the
Attributeinside the loop.