I'm working on a sixth dimensional String array in java and after populating a fourth dimensional array manually I wanted to use Array.fill() to save myself time and well a tedious amount of work. I've tried numerous online "solutions" as well as for/enhanced for loops to no avail. I keep receiving exception 3130 (Exception in thread "main" java.lang.ArrayStoreException: java.lang.String). Any help or insight would be greatly appreciated.
Thank you, Ed.
Here is my code:
String colors[][][][][][] = new String[4][4][4][4][4][4];
for (String[][][][][] Red : colors) {
Arrays.fill(Red, (String) "Red");
for (String[][][][][] Blue : colors) {
Arrays.fill(Blue, (String) "Blue");
for (String[][][][][] Green : colors) {
Arrays.fill(Green, (String) "Green");
for (String[][][][][] Yellow : colors) {
Arrays.fill(Yellow, (String) "Yellow");
}
for (String[][][][][] Orange : colors) {
Arrays.fill(Orange, (String) "Orange");
}
for (String[][][][][] White : colors) {
Arrays.fill(White, (String) "White");
}
That type of exception is thrown to
indicate that an attempt has been made to store the wrong type of object into an array of objects.
(From the documentation)
To understand why, you first have to think about what that code means.
String[][][][][][]
is an array of arrays of arrays that contain arrays containing arrays containing strings. So, yeah.
When you iterate over colors
with the enhanced for loop, you take away the leftmost layer, and Red
contains a 5-dimensional String array, i.e an array containing an array containing an array containing an array containing strings. But Arrays.fill
does not take away the outer layers for you, but tries to fill the topmost, i.e. an array holding 4-dimensional Arrays, with strings. Which leads to the exception.
What you need to do instead is unwrap layer after layer of the array-onion and fill the actuals String arrays like so:
String colors[][][][][][] = new String[4][4][4][4][4][4];
for(String[][][][][] layer1 : colors){ // Iterates over all 5D arrays in colors
for (String[][][][] layer2 : layer1){ //Iterates over all 4D arrays in the 5D arrays
for (String[][][] layer3 : layer2){ // 3D
for (String[][] layer4 : layer3){ // 2D
for (String[] actualArray : layer4){ //actual string arrays
Arrays.fill(actualArray, "something");
}
}
}
}
}
So here you are iterating over all 5D arrays, iterate over all the 4D arrays in each of them etc. until you finally fill the 1D arrays with Strings using `Arrays.fill