java add函数,添加进去全部变成最后一组数据

String[] turn1 = idList.split(",");
String[] turn2 = labelList.split(",");
Attribute attribute = new Attribute();
List Temp = new ArrayList();

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));

就是我现在turn1.length只有3组数据,Add进去Temp之后应该是有三组不同的数据才对。但是现在我Add进去之后虽然是有三组对象,但是里面的数据竟然全部是最后一组的数据。
我现在debug模式下看到三次attribute的数据都是不同的,现在是每循环一次当前的attribute就会把Temp里面的前一组数据给覆盖掉,这是为什么?

输出数据
isPK=false,oid=0,id=1354,name=,label=额定电压
isPK=false,oid=0,id=1354,name=,label=额定电压
isPK=false,oid=0,id=1354,name=,label=额定电压

Attribute attribute = new Attribute();

应该放在
for(int i=0;i<turn1.length;i++){
Attribute attribute = new Attribute();
}

否则你只new了一个 for循环的每一次都修改你的for循环外部的attribute, 因此最后一次修改覆盖了之前的所有(List中的数据都是同引用)

你那样的话 在 for循环之前 new 对象,而 list.add的时候 加的是 对象的地址,你每个循环改变 值 ,但是 地址是没有变的 ,所以你 for循环之前 需要 new一个对象

[code="java"]Attribute attribute=null;
for(int i=0;i<turn1.length;i++){
attribute=new Arrtrbute();
long getId;
getId = Integer.parseInt(turn1[i]);
attribute.setId(getId);
attribute.setLabel(turn2[i]);
Temp.add(attribute);
} [/code]

照1楼或者2楼说的改就可以了,建议你去翻资料搞清楚java的引用类型和基本类型的概念,不要停留在“知其然而不知其所以然”的地步上,搞明白为什么这样才会有进步。

因为你在for外面new 的 Attribute,所以for里每次都是同一个对象attribute。Temp存的是attribute 的引用,当attribute 变化时,在for的三次里,存的都是同一个attribute,Temp里的引用是不变的,始终都指向attribute。所以你看到的都是第三次的结果。