Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate objects are added to the list [duplicate]

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

like image 692
Kartheek s Avatar asked Jul 24 '15 02:07

Kartheek s


2 Answers

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());
}
like image 161
Cacho Santa Avatar answered Sep 18 '22 22:09

Cacho Santa


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.

like image 42
VirtualMichael Avatar answered Sep 21 '22 22:09

VirtualMichael