Does anybody know why Java 1.6 has this behaviour:
List<String> list = ArrayList<String>(); String[] arr = (String[]) list.toArray();
And I get a ClassCastException, because it returns Object[] and not String[].
I thought List<T>.toArray()
should return T[] - no? Does anyone have an answer why this inconvenience exists in the language? And also how to work around this? How do I get a String[] from List<String>
without looping thru the items?
The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.
public <T> T[] toArray(T[] a) The toArray() method is used to get an array which contains all the elements in ArrayList object in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein.
You need to pass in an array so its runtime type can be used as a hint by toArray
. Try toArray(new String[0])
instead. You can also pass in a pre-sized array.
To understand, consider what type erasure would have to do to make
new T[4]
work. If Java allowed that, the best it could do post erasure is
new Object[4]
Most toArray
implementations use java.lang.reflect.Array
to construct an output array of the right type given a type hint passed as a Class
.
Because arrays have been in Java since the beginning, while generics were only introduced in Java 5. And the List.toArray()
method was introduced in Java 1.2, before generics existed, and so it was specified to return Object[]
. Lots of existing code now expects List.toArray()
to return Object[]
, so it can't be changed now.
Furthermore, generics are erased at runtime, so ArrayList
couldn't even construct an array of the proper type if it wanted to.
The loophole for this is the List.toArray(T[])
method, which will return you an array of the correct type, provided you give it an array of the correct type so it knows what type to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With