Duplicate objects are added to the list [duplicate

2019-01-20 15:34发布

This question already has an answer here:

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

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

        //}

    }
}

here

4条回答
聊天终结者
2楼-- · 2019-01-20 15:36

Your problem is that you're referencing the same object cause you created the object before the loop. Should be

public static void main(String args[]) {

    ArrayList<Modelclass> al = new ArrayList<Modelclass>();


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

        //}

    }
}
查看更多
Explosion°爆炸
3楼-- · 2019-01-20 15:47

You are always adding the same

Modelclass obj = new Modelclass();

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

Since it is always a reference to the same object, you are modifying all of the items in the ArrayList.

Try this instead:

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());
}
查看更多
倾城 Initia
4楼-- · 2019-01-20 15:53

I guess you are new in Java? Just create new instances in the loop will work.

ArrayList<ModelClass> al = new ArrayList<ModelClass>();
for(int i=0; i<10; i++){
    ModelClass obj = new ModelClass();
    obj.setName(2+i);
    obj.setRoolno(4+i);
    al.add(obj);
}
查看更多
姐就是有狂的资本
5楼-- · 2019-01-20 16:01

Your obj variable is only being instantiated once, but being added to the list multiple times. Whenever you update the members of obj, you are updating the same piece of memory and thus every list reference shows the same (last added) data.

查看更多
登录 后发表回答