Bryan
Bryan

Reputation: 79

break array into sub array

I have an array, for example:

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

I want to break it into sub array. When I do testing it, it displayed error:

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

Code:

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

Upvotes: 3

Views: 1912

Answers (2)

FThompson
FThompson

Reputation: 28707

From the java.lang.ArrayStoreException documentation:

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

You are attempting to store a String[][] into a String[]. The fix is simply in the return type, and the type passed to the toArray method.

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

Upvotes: 2

MadProgrammer
MadProgrammer

Reputation: 347332

Change

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

to

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

You'll need to change your return type to be String[][]

Upvotes: 2

Related Questions