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

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

问题描述

虽然对象添加到列表中我能看到物体替换列表中的所有值。

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

请检查下面的图片,并在for循环中的列表对象的副本注意code。

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天全站免登陆