From the documentation of Object#clone()
:
Note that all arrays are considered to implement the interface
Cloneable
. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.
But the documentation of java.util.Arrays
doesn't indicate that Arrays implements Cloneable
.
How do arrays implement Cloneable
?
A class implements the Cloneable interface to indicate to the Object. clone() method that it is legal for that method to make a field-for-field copy of instances of that class.
Cloneable interface is implemented by a class to make Object. clone() method valid thereby making field-for-field copy. This interface allows the implementing class to have its objects to be cloned instead of using a new operator.
If a class which implements Cloneable does override the Object.clone() method, usually a super.clone() will be called first to make a binary copy of the original object and then deep copy will be performed accordingly based on the binary copy. See below example: 1.
You are confusing java.util.Arrays
, a normal class that contains methods to work with arrays, and arrays themselves, which are a rather special construct in the Java language but are nonetheless objects with a synthetic class. This is this class that implements Cloneable
. It also derives directly from Object
. Look at the JLS page on arrays which is pretty clear on the subject.
Look for example at this code (taken from the aforementionned JLS):
class Test {
public static void main(String[] args) {
int[] ia = new int[3];
System.out.println(ia.getClass());
System.out.println(ia.getClass().getSuperclass());
}
}
This will print:
class [I
class java.lang.Object
java.util.Arrays
is a class containing utilities that operate on Java arrays, and is not to be confused with arrays themselves.
An array is a container object that holds a fixed number of values of a single type. They are a special type of Object defined explicitly in the Java language. All Java arrays implement java.lang.Cloneable
and java.io.Serializable
.
java.util.Arrays
, on the other hand, does not implement these interfaces, and only provides static methods that implement common functions performed on arrays.
When you clone a single dimensional array, such as Object[]
, a "deep copy" is performed with the new array containing copies of the original array's elements as opposed to references.
A clone of a multidimensional array (like Object[][]
) is a "shallow copy" however, which is to say that it creates only a single new array with each element array a reference to an original element array.
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