Search code examples
javaarraylistclone

Clonning ArrayList element to the same ArrayList


I have an ArrayList that contains objects. (this objects are clases, every object contains an incredibly large amount of information, precisely these object represent large electric generators, so copying the properties one by one is not an option).

example:

ArrayList arr = {ob1, ob2, ob3, ob4, ob5}

So what I try to do is to clone the object (ob1) to the position 5.

arr.set(4, arr.get(0));

But somehow, doing that, ob5 is not a copy ob ob1, it is ob1, so if I change ob5, ob1 changes too.

Is this something inherent to ArrayLists? Is there any difference if I use Lists instead?


Solution

  • This is because you are doing a shadow copy instead of a deep copy.

    Shallow copy: If a shallow copy is performed on Obj-1 then it is copied but its contained objects are not. The contained objects Obj-1 and Obj-2 are affected by changes to cloned Obj-2. Java supports shallow cloning of objects by default when a class implements the java.lang.Cloneable interface.

    Deep copy: If a deep copy is performed on obj-1 as shown then not only obj-1 has been copied but the objects contained within it have been copied as well. Serialization can be used to achieve deep cloning. Deep cloning through serialization is faster to develop and easier to maintain but carries a performance overhead. source

    An example of Deep Copy:

    class Student implements Cloneable {
      //Contained object
      private Subject subj;
      private String name;
    
      public Subject getSubj() {..}
      public String getName() {..}
    
      public Object clone() {
        //Deep copy
        Student s = new Student(name, subj.getName());
        return s;
      }
    }