为什么List< String> .toArray()返回Object []而不是String []?如何解决这个问题? [英] why does List<String>.toArray() return Object[] and not String[]? how to work around this?
问题描述
有人知道为什么Java 1.6有这种行为:
Does anybody know why Java 1.6 has this behaviour:
List<String> list = ArrayList<String>();
String[] arr = (String[]) list.toArray();
我得到一个ClassCastException,因为它返回Object []而不是String []。
And I get a ClassCastException, because it returns Object[] and not String[].
我以为
List< T> .toArray()
应该返回T [] - no?有没有人有答案为什么这种不便在语言中存在?
还有如何解决这个问题?如何从 List< String>
得到一个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?
推荐答案
您需要传入一个数组,以便它的运行时类型可以用作 toArray
的提示。尝试 toArray(new String [0])
来代替。你也可以传入一个预先设定大小的数组。
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]
工作。如果Java允许的话,它可以在擦除后进行最好的处理是:
work. If Java allowed that, the best it could do post erasure is
new Object[4]
大多数 toArray
实现使用 java.lang.reflect.Array中
来构造一个给定类型提示的正确类型的输出数组,该类型提示作为 Class
传递。
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
.
这篇关于为什么List< String> .toArray()返回Object []而不是String []?如何解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!