为什么下面的代码无法执行,但它不会检测为来自 IDE 的错误。它会编译得很好。
ArrayList<String> a = new ArrayList<String>();
a.add("one");
a.add("two");
a.add("three");
String [] b = (String[])a.toArray();
for(int i =0;i<b.length;++i){
System.out.println(b[i]);
}
但是会报如下错误。
nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
谁能给个明确的解释?之前有人问过同样的问题,并提供了一些解决方案。但对问题的明确解释将不胜感激。
最佳答案
你应该简单地做:
String[] b = new String[a.size()];
a.toArray(b);
你收到错误是因为 toArray()
返回 Object[]
并且不能转换为 String[]
。
关于java - ArrayList 无法使用 (String[])list.toArray() 转换为字符串数组。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20119170/