jxie0755
jxie0755

Reputation: 1742

Why does ArrayList have a clone method

I am not sure I understand the purpose of clone() in ArrayList.

there are many ways to make a shallow copy of an ArrayList, I know at least two:

List<Integer> L1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
List<Integer> L1_copy = new ArrayList<>(L1);
List<Integer> L1_copy2 = List.copyOf(L1);   // inmutable but solve by below:
List<Integer> L1_copy3 = new ArrayList<>(List.copyOf(L1));

It is also surprising that this returns an Object, instead of an ArrayList, And I have to downcast:

ArrayList<Integer> AL1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
ArrayList<Integer> AL1_copy = (ArrayList<Integer>) AL1.clone();

Why is it designed to be returning as an Object? Any advantage of using the clone over other shallow copy method?

Upvotes: 1

Views: 379

Answers (3)

Andy Thomas
Andy Thomas

Reputation: 86411

In general, a public clone() method supports polymorphism. You can call it on a reference of a superclass type, to clone an object of any subclass type.

Why is it designed to be returning as an Object?

Covariant return types were introduced in Java 5. ArrayList was introduced earlier, in Java 2.

ArrayList is not a final class. Modifying its return type to return ArrayList could have broken third-party subclasses.

Any advantage of using the clone over other shallow copy method?

Polymorphism.

Upvotes: 0

Thomas Bitonti
Thomas Bitonti

Reputation: 1234

The typing is a result of ArrayList being written before java 5. Before java 5, the return type of an overriding method had to be the same as the method which was being overridden (was invariant). Today, since method return types can be specialized (are covariant), if ArrayList were being rewritten, it should be written with ArrayList as the return type.

However, there is a deep problem here, which is that while an implementation can specialize clone()'s return type, the type system hasn't expressed the typing relationship fully. What would be better would be a "self" type, which java only marginally supports. That gets you pretty deep into typing theory. See, for example: Java self-typed methods: cannot safely cast to actual type.

From a utility perspective, as others have said, Cloneable has turned out to not be a very useful API. In practice, there tend to be too many particulars to how one wants copy to work for a single API to fit all of those particulars.

Upvotes: 2

rknife
rknife

Reputation: 300

I don't think there is an added advantage because of the presence of the clone() method. In the case of primitives, it would equate to a deep copy. Also, I did not know these many methods in Java except the constructor one, in which you pass the Collection as an argument in the constructor. It also implements the Cloneable interface which I think is like a marker interface. It returns Object because it is the superclass of all classes and returning it would not break the code.

Upvotes: 2

Related Questions