java: (String[])List.toArray() 给出 ClassCastException
下面的代码(在android中运行)总是在第三行给我一个ClassCastException:
final String[] v1 = i18nCategory.translation.get(id);
final ArrayList<String> v2 = new ArrayList<String>(Arrays.asList(v1));
String[] v3 = (String[])v2.toArray();
当v2是Object[0]并且其中有字符串时也会发生这种情况。 知道为什么吗?
The following code (run in android) always gives me a ClassCastException in the 3rd line:
final String[] v1 = i18nCategory.translation.get(id);
final ArrayList<String> v2 = new ArrayList<String>(Arrays.asList(v1));
String[] v3 = (String[])v2.toArray();
It happens also when v2 is Object[0] and also when there are Strings in it.
Any Idea why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是因为当您使用
它时,它返回一个 Object[],它不能转换为 String[] (即使内容是字符串)这是因为 toArray 方法只获取 a
而不是
因为泛型只是源代码事物,并且在运行时不可用,因此它无法确定要创建什么类型的数组。
use
分配正确类型的数组(String[] 和正确的大小)
This is because when you use
it returns an Object[], which can't be cast to a String[] (even tho the contents are Strings) This is because the toArray method only gets a
and not
as generics are a source code only thing, and not available at runtime and so it can't determine what type of array to create.
use
which allocates the right kind of array (String[] and of the right size)
您使用了错误的
toArray()
请记住,Java 的泛型主要是语法糖。 ArrayList 实际上并不知道它的所有元素都是字符串。
要解决您的问题,请调用
toArray(T[])
。在您的情况下,请注意,泛型形式
toArray(T[])
返回T[]
,因此不需要显式转换结果。You are using the wrong
toArray()
Remember that Java's generics are mostly syntactic sugar. An ArrayList doesn't actually know that all its elements are Strings.
To fix your problem, call
toArray(T[])
. In your case,Note that the genericized form
toArray(T[])
returnsT[]
, so the result does not need to be explicitly cast.也能做到这一点,
请注意,一旦为该方法提供了正确的 ArrayType,您甚至不需要再进行强制转换。
also does the trick,
note that you don't even need to cast anymore once the right ArrayType is given to the method.
使用 JDK 11 Stream API,您可以这样解决更一般的问题:
Using
toArray
from the JDK 11 Stream API, you can solve the more general problem this way:像这样使用。
Use like this.