Tobias Johansson
Tobias Johansson

Reputation: 376

clone() method in ArrayList, why Arrays.copyOf()?

I try to get my head straight about cloning in Java with my own ArrayList.

For what I see this code

@Override
public Object clone() {
    try {
        MyArrayList<E> v = (MyArrayList<E>) super.clone();
        v.elementData = Arrays.copyOf(elementData, size);
        return v;
    } catch (CloneNotSupportedException e) {
        throw new InternalError();
    }
}

Gives the same result as

@Override
public Object clone() {
    try {
        return (MyArrayList<E>) super.clone();
    } catch (CloneNotSupportedException e) {
        throw new InternalError();
    }
}

Am I doing something wrong or why use the Arrays.copyOf()?

Upvotes: 1

Views: 1763

Answers (1)

Nir Alfasi
Nir Alfasi

Reputation: 53525

No it doesn't, the first method creates a copy of the underlying array (attention: it's a copy of the array - not the objects in the array!).

The latter creates an ArrayList that points to the same array as the original object.

Example:

    String[][] s1 = {{new String("a"), new String("b")}};
    String[][] s2 = s1.clone();
    System.out.println(Arrays.toString(s1)); // prints [[Ljava.lang.String;@7440e464]
    System.out.println(Arrays.toString(s2)); // prints [[Ljava.lang.String;@7440e464]
    System.out.println(s1[0] == s2[0]); // prints true
    System.out.println(s1 == s2); // prints false - because s2 != s1

Since the array of arrays is an object, and the item in the first place (s[0]) is an array itself (which is an object as well) - you can see that clone simply copied the reference to the objects.

Upvotes: 3

Related Questions