Why does Collection<E>#toArray() not return E[]?

arrays, collections, generics, java

Solution

It's because an array of type `T` cannot be instantiated without knowing the type `Class<T>`. Contrast this with `toArray(T[] array)`, which has the following source (example from `LinkedList`). Notice that the passed-in array is used not only as a possible container, but to possibly instantiate a new array of that type. This code throws an exception if `T` is not a superclass of `E`; if objects can't be added to the array.

@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
    if (a.length < size)
        a = (T[])java.lang.reflect.Array.newInstance(
                            a.getClass().getComponentType(), size);
    int i = 0;
    Object[] result = a;
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;

    if (a.length > size)
        a[size] = null;

    return a;
}

Problem

Why does `Collection<E>.toArray()` (non-parameterized method) return `Object[]`? Is it one of those consciously taken decisions? Is there any reason why the `toArray()` method would not be able to return a `E[]`, if it wanted to?

Original source

Related problems