[英]java add function,all become one last set of data when added
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. 依次只有1组3个数据。长度,在添加temp时,应该有3组不同的数据。但是,在我添加后,即使有3个组对象,其中的日期也可能是最后一组日期,所有。 I see three different data in debug mode,current attribute will cover the prev data in temp each cycle.
我在调试模式下看到三个不同的数据,current属性将覆盖每个周期中temp的上一个数据。
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 Attribute
inside the loop. 您应该做的是在循环内添加新的
Attribute
。
String[] turn1 = idList.split(",");
String[] turn2 = labelList.split(",");
List<Attribute> Temp = new ArrayList<Attribute>();
for(int i=0;i<turn1.length;i++){
long getId;
Attribute attribute = new Attribute();
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.