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;
}
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With