Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

clone

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?

like image 483
Szymon Avatar asked Apr 28 '11 16:04

Szymon


People also ask

Does clone () make a deep copy?

clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.

How do I copy the contents of an array?

If you want to copy the first few elements of an array or a full copy of an array, you can use Arrays. copyOf() method. Arrays. copyOfRange() is used to copy a specified range of an array.

Can you clone an array?

Answer: There are different methods to copy an array. You can use a for loop and copy elements of one to another one by one. Use the clone method to clone an array. Use arraycopy() method of System class.

What is clone () method?

clone() method in Java Assignment operator has a side-effect that when a reference is assigned to another reference then a new object is not created and both the reference point to the same object. This means if we change the value in one object then same will reflect in another object as well.


2 Answers

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   -----   
like image 62
Bozho Avatar answered Sep 19 '22 08:09

Bozho


If I invoke clone() method on array of Objects of type A, how will it clone its elements?

The elements of the array will not be cloned.

Will the copy be referencing to the same objects?

Yes.

Or will it call (element of type A).clone() for each of them?

No, it will not call clone() on any of the elements.

like image 45
Bludzee Avatar answered Sep 22 '22 08:09

Bludzee