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

collections, generics, java

Solution

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.

Problem

`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`?

Original source

Related problems