java: (String[])List.toArray() 给出 ClassCastException [英] java: (String[])List.toArray() gives ClassCastException

查看:35
本文介绍了java: (String[])List.toArray() 给出 ClassCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码(在 android 中运行)总是在第三行给我一个 ClassCastException:

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();

当 v2 是 Object[0] 并且其中有字符串时也会发生这种情况.知道为什么吗?

It happens also when v2 is Object[0] and also when there are Strings in it. Any Idea why?

推荐答案

这是因为当你使用

 toArray() 

它返回一个对象[],它不能被转换为一个字符串[](即使内容是字符串)这是因为toArray方法只得到一个

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

List 

而不是

List<String>

因为泛型只是一个源代码,在运行时不可用,因此它无法确定要创建什么类型的数组.

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.

使用

toArray(new String[v2.size()]);

分配正确类型的数组(String[] 和正确大小)

which allocates the right kind of array (String[] and of the right size)

这篇关于java: (String[])List.toArray() 给出 ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆