java字符串数组的字符串列表

时间:2013-09-11 10:42:31

标签: java android list arraylist classcastexception

我想知道是否可以将List的{​​{1}}转换为String的数组:

我试过了:

String

但它给了我一条例外消息:

  

java.lang.ClassCastException:java.lang.Object []无法强制转换为java.lang.String []

4 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:2)

使用

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

products.toArray()会将列表值放在Object[]数组中,与您不能将超类型对象转换为派生类型相同,如

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

您无法将Object[]数组存储或转换为String[]数组,因此您需要传递要返回的确切类型的数组。

其他信息here

答案 2 :(得分:0)

尝试

List<String> products = new ArrayList<String>();
        String[] arrayCategories = products.toArray(new String[products.size()]);

答案 3 :(得分:0)

这应该可以解决问题。你在第一行写了一个拼写错误。

List<String> products = new ArrayList<>();
String[] array = (String[]) products.toArray();
相关问题