重复的对象被添加到列表中

在向列表添加对象时,我能够看到该对象正在替换列表中的所有值。

请检查下面的图像,并注意列表中对象重复的for循环代码。

public static void main(String args[]) { ArrayList al = new ArrayList(); 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()); //} } } 

这里

你总是添加相同的

 Modelclass obj = new Modelclass(); 

你在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()); } 

你的obj变量只被实例化一次,但被多次添加到列表中。 每当更新obj的成员时,您都在更新同一块内存,因此每个列表引用都显示相同(最后添加的)数据。

我猜你是Java新手? 只需在循环中创建新实例即可。

 ArrayList al = new ArrayList(); for(int i=0; i<10; i++){ ModelClass obj = new ModelClass(); obj.setName(2+i); obj.setRoolno(4+i); al.add(obj); } 

您的问题是您引用了相同的对象,因为您在循环之前创建了对象。 应该

 public static void main(String args[]) { ArrayList al = new ArrayList(); for (int i = 0; i < 10; i++) { Modelclass obj = new Modelclass(); 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()); //} } }