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

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

问题描述

以下代码(在android中运行)总是在第3行给出一个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() 

它返回一个Object [ ],无法强制转换为String [](即使内容是字符串)这是因为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天全站免登陆