在类数组中抛出的类转换异常

时间:2015-04-15 11:03:33

标签: java arrays arraylist casting

我只是将两个字符串数组附加到一个数组列表中,然后将其转换为字符串数组以将返回变量作为string[]传递

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();
    }    


}

错误来了

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at myFirst.myClass.main(myClass.java:26)

如何解决这个问题。亲切帮助我

4 个答案:

答案 0 :(得分:3)

您需要在数组中单独转换每个成员,因为结果是Object []而不是String []

或者只是做

String [] outResult= listString.toArray(new String[listString.size()]);

答案 1 :(得分:0)

使用

String[] outResult = (String[]) listString.toArray(new String[0]);

答案 2 :(得分:0)

尝试以下解决方案:

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();
    }    


}

答案 3 :(得分:-1)

listString.toArray();将返回Object[],而不是String[]