3

我有一个数组,例如:

{ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }

我想把它分解成子数组。当我测试它时,它显示错误:

java.lang.ArrayStoreException at line: String[] strarray = splitted.toArray(new String[0]);

代码:

public static String[] splittedArray(String[] srcArray) {
        List<String[]> splitted = new ArrayList<String[]>();
        int lengthToSplit = 3;
        int arrayLength = srcArray.length;

        for (int i = 0; i < arrayLength; i = i + lengthToSplit) {
            String[] destArray = new String[lengthToSplit];
            if (arrayLength < i + lengthToSplit) {
                lengthToSplit = arrayLength - i;
            }
            System.arraycopy(srcArray, i, destArray, 0, lengthToSplit);
            splitted.add(destArray);
        }
        String[] strarray = splitted.toArray(new String[0]);
        return strarray;
    }
4

2 回答 2

2

改变

String[] strarray = splitted.toArray(new String[0]);

String[][] split = new String[splitted.size()][lengthToSplit];
for (int index = 0; index < splitted.size(); index++) {
    split[index] = splitted.get(index);
}

您需要将返回类型更改为String[][]

于 2012-08-09T07:29:22.203 回答
2

java.lang.ArrayStoreException 文档中:

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

您正在尝试将 String[][] 存储到 String[] 中。修复只是在返回类型和传递给toArray方法的类型。

String[][] strarray = splitted.toArray(new String[0][0]);
于 2012-08-09T07:32:01.583 回答