3

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;
    }
1
  • 1
    splitted is a list of arrays. I think you need to do something like splitted.get(0) or splitted.toArray(new String[][]) - but I'm pretty sure you can't do that :P Commented Aug 9, 2012 at 7:25

2 Answers 2

2

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]);
Sign up to request clarification or add additional context in comments.

Comments

2

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[][]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.