Twisted Meadow
Twisted Meadow

Reputation: 443

when casting is need for clone() method?

consider the code below:

ArrayList<Double> list1 = new ArrayList<>();
list1.add(1.5);
list1.add(2.5);
list1.add(3.5);
ArrayList<Double> list2 = (ArrayList<Double>)list1.clone();

Date[] list3 = {new Date(), new Date(4664316)};
Date[] list4 = list3.clone();

int[] list5 = {1, 2};
int[] list6 = list5.clone();

why list.clone() requires casting, while list3.clone() and list5.clone() don't need casting? I know the difference is between array and ArrayList, but not sure exactly why.

Upvotes: 2

Views: 822

Answers (2)

Jerome Anthony
Jerome Anthony

Reputation: 8021

Clone() method signature returns an object type.

By convention, the object returned by this method should be independent of this object (which is being cloned)

Hence the cast is required.

Arrays behave differently and return a correctly typed clone array. So no casting required.

Upvotes: 0

tonychow0929
tonychow0929

Reputation: 466

Please read the documentation.

Note that all arrays are considered to implement the interface Cloneable and that the return type of the clone method of an array type T[] is T[] where T is any reference or primitive type.

But in ArrayList, an Object is returned, so a cast is needed.

Upvotes: 3

Related Questions