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

java字符串列表到字符串数组,java,android,list,arraylist,classcastexception,Java,Android,List,Arraylist,Classcastexception,我想知道是否可以将Strings的JavaList转换为Strings的数组: 我试过这个: List<String> products = new ArrayList<String>(); //some codes.. String[] arrayCategories = (String[]) products.toArray(); List products=new ArrayList(); //一些代码。。 String[]arrayCategories=(Str

我想知道是否可以将
String
s的Java
List
转换为
String
s的数组:

我试过这个:

List<String> products = new ArrayList<String>();
//some codes..
String[] arrayCategories = (String[]) products.toArray();
List products=new ArrayList();
//一些代码。。
String[]arrayCategories=(String[])products.toArray();
但它给了我一个例外信息:

java.lang.ClassCastException:java.lang.Object[]不能转换为java.lang.String[]

使用

products.toArray()
将把列表值放入
Object[]
数组,这与不能将超级类型的对象强制转换为其派生类型相同

//B extands A
B b = new A();
无法将
对象[]
数组存储或强制转换为
字符串[]
数组,因此需要传递要返回的确切类型的数组

其他信息。

请尝试

List products=new ArrayList();
String[]arrayCategories=products.toArray(新字符串[products.size()]);

这应该可以做到。你在第一行有个打字错误

List<String> products = new ArrayList<>();
String[] array = (String[]) products.toArray();
List products=new ArrayList();
String[]数组=(String[])products.toArray();

@LalitPoptani我发现的副本更好:DDuplicate是副本更好还是更差:p这里的问题不是数组转换,而是在新的ArrayList[String]()上错误地使用了[],它应该是新的ArrayList()。。我正要回答,但你们把这个关了..嗯。现在,我的编辑是错误的,这是正确的。愿它一直关着,它也给了我同样的感觉Exception@MouadELFakir,那么你可能做错了别的事情。发布你的代码来检查你弄乱了什么是的,谢谢我刚刚发现我遗漏了什么,我只是忘记填写我的产品列表我让它空了,它现在工作很好,谢谢你;)@MouadELFakir,如果这个答案对你有效,你可以把它标记为答案
String[] array = products.toArray(new String[products.size()]);
List<String> products = new ArrayList<String>();
        String[] arrayCategories = products.toArray(new String[products.size()]);
List<String> products = new ArrayList<>();
String[] array = (String[]) products.toArray();