Kar*_*k s 3 java collections core arraylist
将对象添加到列表中时,我能够看到该对象正在替换列表中的所有值。
请检查下图,并注意for循环中的代码,其中包含列表中对象的重复项。
public static void main(String args[]) {
ArrayList<Modelclass> al = new ArrayList<Modelclass>();
Modelclass obj = new Modelclass();
for (int i = 0; i < 10; i++) {
obj.setName(2 + i);
obj.setRoolno(4 + i);
System.out.println(obj);
//if (!al.equals(obj)) {
al.add(obj);
System.out.println(obj.getName() + "" + obj.getRoolno());
//}
}
}
Run Code Online (Sandbox Code Playgroud)
您总是添加相同的
Modelclass obj = new Modelclass();
Run Code Online (Sandbox Code Playgroud)
您在for循环之外创建的。然后,在循环内部,您正在修改值。
由于它始终是对同一对象的引用,因此您正在修改ArrayList中的所有项目。
尝试以下方法:
for (int i = 0; i < 10; i++) {
Modelclass obj = new Modelclass(); //This is the key to solve it.
obj.setName(2 + i);
obj.setRoolno(4 + i);
System.out.println(obj);
al.add(obj);
System.out.println(obj.getName() + "" + obj.getRoolno());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2619 次 |
| 最近记录: |