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?
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.
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.
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.
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.
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 -----
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With