Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why <T> for toArray hides <E> of Collection<E>?

toArray method hides <E> passed to Collection<E> interface. Below is the method signature.

<T> T[] toArray(T[] a);

Because of which below is possible. And results into ArrayStoreException

ArrayList<String> string = new ArrayList<String>();
string.add("1");
string.add("2");
Integer intArray[] = new Integer[2];
intArray = string.toArray(intArray);

I wanted to know why was such decision taken? Why was such a case allowed while designing the API ? As anyway this code results in to RuntimeException?

like image 281
Amit Deshpande Avatar asked Nov 03 '22 12:11

Amit Deshpande


1 Answers

The toArray method predates the introduction of generics. The original signature of toArray took an arbitrary Object[].

This is the only way, with generics, to accept the same input that was permissible before generics. However, the advantage of taking an arbitrary T[] is that it can return the same array type that it's passed.

like image 140
Louis Wasserman Avatar answered Nov 12 '22 19:11

Louis Wasserman