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?
You need to pass in an array so its runtime type can be used as a hint by
toArray. TrytoArray(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
work. If Java allowed that, the best it could do post erasure is
Most
toArrayimplementations usejava.lang.reflect.Arrayto construct an output array of the right type given a type hint passed as aClass.