重复的对象被添加到列表中 [英] Duplicate objects are added to the list

查看:42
本文介绍了重复的对象被添加到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

While adding objects to list I was able to see the object is replacing all values in the list.

请检查下图并注意for循环中的代码是否存在列表中对象的重复项.

Please check the below image and notice the code in for loop for duplicates of object in the list.

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

        //}

    }
}

推荐答案

你总是添加相同的

Modelclass obj = new Modelclass();

您在 for 循环之外创建的.然后,在循环内,您正在修改值.

That you created outside of the for loop. Then, inside the loop, you are modifying the values.

由于它始终是对同一对象的引用,因此您正在修改 ArrayList 中的所有项目.

Since it is always a reference to the same object, you are modifying all of the items in the 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());
}

这篇关于重复的对象被添加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆