Does calling clone() on an array also clone its contents?

Szymon picture Szymon · Apr 28, 2011 · Viewed 102.4k times · Source

If I invoke clone() method on array of Objects of type A, how will it clone its elements? Will the copy be referencing to the same objects? Or will it call (element of type A).clone() for each of them?

Answer

Bozho picture Bozho · Apr 28, 2011

clone() creates a shallow copy. Which means the elements will not be cloned. (What if they didn't implement Cloneable?)

You may want to use Arrays.copyOf(..) for copying arrays instead of clone() (though cloning is fine for arrays, unlike for anything else)

If you want deep cloning, check this answer


A little example to illustrate the shallowness of clone() even if the elements are Cloneable:

ArrayList[] array = new ArrayList[] {new ArrayList(), new ArrayList()};
ArrayList[] clone = array.clone();
for (int i = 0; i < clone.length; i ++) {
    System.out.println(System.identityHashCode(array[i]));
    System.out.println(System.identityHashCode(clone[i]));
    System.out.println(System.identityHashCode(array[i].clone()));
    System.out.println("-----");
}

Prints:

4384790  
4384790
9634993  
-----  
1641745  
1641745  
11077203  
-----