Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does List<String>.toArray() return Object[] and not String[]? how to work around this?

Tags:

java

generics

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?

like image 543
justadreamer Avatar asked Oct 26 '11 22:10

justadreamer


People also ask

What is the purpose of toArray ()?

The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.

How does the toArray method work in Java?

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.


2 Answers

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.

like image 185
Mike Samuel Avatar answered Oct 11 '22 09:10

Mike Samuel


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.

like image 45
Daniel Pryden Avatar answered Oct 11 '22 11:10

Daniel Pryden