vxh.viet
10/9/2017 - 5:01 AM

Deep copy

How to deep copy an ArrayList of Object, Integer, arrays, etc..

Source: StackOverflow, StackOverflow, StackOverflow

Question: How to deep copy an ArrayList?

Answer:

Deep copy an ArrayList of Object

Add a constructor to the object that you want to copy

class Dog
{
    public Dog()
    { ... } // Regular constructor

    public Dog(Dog dog) {
        // Copy all the fields of Dog.
    }
}

Then just iterate

public static List<Dog> cloneList(List<Dog> dogList) {
    List<Dog> clonedList = new ArrayList<Dog>(dogList.size());
    for (Dog dog : dogList) {
        clonedList.add(new Dog(dog));
    }
    return clonedList;
}

I find the advantage of this is you don't need to screw around with the broken Cloneable stuff in Java. It also matches the way that you copy Java collections.

Deep copy an ArrayList of Integer

Integer is already immutabale, shallow copy is enough, see StackOverflow

To create an ArrayList b containing the same Integers as another List a, just use the following code:

List<Integer> b = new ArrayList<Integer>(a);

Deep copy an array

int[] src  = new int[]{1,2,3,4,5};
int[] dest = new int[5];

System.arraycopy( src, 0, dest, 0, src.length );