user2488578
user2488578

Reputation: 916

How do Java arrays implement Cloneable?

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?

Upvotes: 5

Views: 2675

Answers (2)

Taylor Hx
Taylor Hx

Reputation: 2833

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.

Upvotes: 4

Cyrille Ka
Cyrille Ka

Reputation: 15523

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

Upvotes: 5

Related Questions