Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java's Collection<E>.toArray() return an Object[] rather than an E[]?

Tags:

Before Java generics, Collection.toArray() had no way to know which type of array the developer expected (particularly for an empty collection). As I understand it, this was the main rationale behind the idiom collection.toArray(new E[0]).

With generics, Collection<E>.toArray() can only return an array full of instances of E and/or its specialisations. I wonder why the return type still is as Object[] rather than E[]. In my opinion, returning an E[] instead of Object[] should not break existing code.

See: Collection.toArray(), Collection.toArray(T[]) and the related topic java: (String[])List.toArray() gives ClassCastException

like image 910
Bernhard Bodenstorfer Avatar asked May 30 '11 07:05

Bernhard Bodenstorfer


2 Answers

It is a very good question. The answer is that generics are also called "erasures." It is not just a name. The information coded by generics is used at compile time only and then is removed. So, JVM even does not know this generic type E, so it cannot create array E[].

Other method toArray(T[] a) receives the information about the type from the argument at runtime. This is the reason this method's prototype is <T> T[] toArray(T[] a): it gets array of type T and can return array of type T. The type is passed as a parameter.

like image 123
AlexR Avatar answered Sep 22 '22 13:09

AlexR


"Type erasure" is only a partial explanation: Neither the Collection, nor its toArray() method have any information about E at run time.

It is also because of backwards compatibility, that Collection.toArray() must still return Object[]. Before Java 1.5, there was no way of knowing a generic type for a collection, so this was the only reasonable API design.

like image 31
Lukas Eder Avatar answered Sep 21 '22 13:09

Lukas Eder