为什么以下列表无法在Java中转换为字符串数组

时间:2014-02-03 15:20:13

标签: java arrays string list

我在Java中有以下代码,当我运行它时,它会给出一些错误:

String[] stringArray1 = {"1","2","3"};
String[] stringArray2 = {"1","3","5"};
String[] stringArray3 = {"1","4","6"};

public String[] getString(int age) {

        List<String> list = new ArrayList<String>();

        switch (age) {
            case 1:

                Collections.addAll(list, stringArray1);
                return composeStrings(list);

            case 2:

                Collections.addAll(list, stringArray2);
                return composeStrings(list);

            case 3:
                Collections.addAll(list, stringArray3);
                return composeStrings(list);

            default:
                return new String[]{"Not find", "Please specify the age"};
            }
    }

public String[] composeStrings(List<String> list) {

        list.add("added a new string");

        return (String[]) list.toArray();
}

但是当我运行它时,它表示行:return (String[]) list.toArray();

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

这是什么问题?以及如何解决它?

2 个答案:

答案 0 :(得分:5)

尝试:

public String[] composeStrings(List<String> list) {

    list.add("added a new string");

    return list.toArray(new String[list.size()]);
}

您可以阅读toArray here

的javadoc

答案 1 :(得分:0)

您必须将String[]作为参数传递给toArray()方法,否则会返回Object[]

public static void main(String[] args) {

        String[] stringArray1 = { "1", "2", "3" };
        String[] stringArray2 = { "1", "3", "5" };
        String[] stringArray3 = { "1", "4", "6" };

        List<String> list = new ArrayList<String>();

        Collections.addAll(list, stringArray1);
        Collections.addAll(list, stringArray2);
        Collections.addAll(list, stringArray3);

        String[] finalArray = list.toArray(new String[list.size()]);
        for (String item : finalArray) {
            System.out.println(item);
        }

    }