class cast exception thrown in string array
本问题已经有最佳答案,请猛点这里访问。
我只是将两个字符串数组附加到一个数组列表中,然后将其转换为字符串数组以将返回变量作为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public static void main(String[] args) { // TODO Auto-generated method stub String [] a = {"america","bakrain","canada"}; String [] b = {"denmark","europe" }; try{ List<String> listString = new ArrayList<String>(Arrays.asList(a)); listString.addAll(Arrays.asList(b)); String [] outResult= (String[])listString.toArray(); System.out.println(outResult); } catch (Exception e) { e.printStackTrace(); } } |
错误来了
1 2 | java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String; at myFirst.myClass.main(myClass.java:26) |
如何解决这个问题,请帮帮我
你会需要individually铸造每一成员在阵列,因为结果是面向[不] [字符串] </P >
或是做 </P >
尝试下面的解决方案: </P >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public static void main(String[] args) { // TODO Auto-generated method stub String [] a = {"america","bakrain","canada"}; String [] b = {"denmark","europe" }; try{ List<String> listString = new ArrayList<String>(Arrays.asList(a)); listString.addAll(Arrays.asList(b)); System.out.println(listString); String [] outResult= new String[listString.size()]; int i=0; for(String str: listString){ outResult[i]=str; i++; } } catch (Exception e) { e.printStackTrace(); } } |
使用 </P >