gpt4 book ai didi

java - ArrayList 无法使用 (String[])list.toArray() 转换为字符串数组。为什么?

转载 作者:行者123 更新时间:2023-12-03 23:13:07 24 4
gpt4 key购买 nike

为什么下面的代码无法执行,但它不会检测为来自 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com