将 Java 中的字符串列表转换为字符串数组

28 浏览
0 Comments

将 Java 中的字符串列表转换为字符串数组

这个问题已经有答案了:

将 ArrayList 转换为 String[] 数组 [重复]

在 Java 中将 \'ArrayList\' 转换为 \'String[]\'

在 Java 中将 List 转换为 String[]

我想知道是否可能将 Java 中的 ListString 转换为 String 数组:

我尝试过这样:

List products = new ArrayList();
//some codes..
String[] arrayCategories = (String[]) products.toArray();

但是它给我一个异常消息:

java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]

admin 更改状态以发布 2023年5月23日
0
0 Comments

使用

String[] arrayCategories = products.toArray(new String[products.size()]);

products.toArray() 将把列表值放入 Object[] 数组中,和你不能将超类型的对象转换为其派生类型一样,如

//B extands A
B b = new A();

你不能将 Object[] 数组存储或转换为 String[] 数组,因此您需要传递精确类型的数组以返回所需的类型。

更多信息请看这里

0
0 Comments

String[] array = products.toArray(new String[products.size()]);

0