The following code (run in android) always gives me a ClassCastException in the 3rd line:
下面的代码(在android中运行)总是在第三行给我一个ClassCastException:
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?
它也发生在v2是对象[0]的时候,也发生在其中有字符串的时候。知道为什么吗?
2 个解决方案
#1
195
This is because when you use
这是因为当你使用时。
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
它返回一个对象[],它不能被转换为String[](甚至tho内容是字符串),这是因为toArray方法只获得a。
List
and not
而不是
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.
泛型是一种源代码,但在运行时不可用,因此无法确定要创建的数组类型。
use
使用
toArray(new String[v2.size()]);
which allocates the right kind of array (String[] and of the right size)
它分配正确的数组(字符串[]和正确的大小)
#2
29
You are using the wrong toArray()
您使用的是错误的toArray()
Remember that Java's generics are mostly syntactic sugar. An ArrayList doesn't actually know that all its elements are Strings.
请记住,Java的泛型主要是语法糖。ArrayList并不知道它的所有元素都是字符串。
To fix your problem, call toArray(T[])
. In your case,
要解决您的问题,请调用toArray(T[])。在你的情况下,
String[] v3 = v2.toArray(new String[v2.size()]);
Note that the genericized form toArray(T[])
returns T[]
, so the result does not need to be explicitly cast.
注意,genericized表单toArray(T[])返回T[],因此结果不需要显式地转换。
#1
195
This is because when you use
这是因为当你使用时。
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
它返回一个对象[],它不能被转换为String[](甚至tho内容是字符串),这是因为toArray方法只获得a。
List
and not
而不是
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.
泛型是一种源代码,但在运行时不可用,因此无法确定要创建的数组类型。
use
使用
toArray(new String[v2.size()]);
which allocates the right kind of array (String[] and of the right size)
它分配正确的数组(字符串[]和正确的大小)
#2
29
You are using the wrong toArray()
您使用的是错误的toArray()
Remember that Java's generics are mostly syntactic sugar. An ArrayList doesn't actually know that all its elements are Strings.
请记住,Java的泛型主要是语法糖。ArrayList并不知道它的所有元素都是字符串。
To fix your problem, call toArray(T[])
. In your case,
要解决您的问题,请调用toArray(T[])。在你的情况下,
String[] v3 = v2.toArray(new String[v2.size()]);
Note that the genericized form toArray(T[])
returns T[]
, so the result does not need to be explicitly cast.
注意,genericized表单toArray(T[])返回T[],因此结果不需要显式地转换。