zach zach - 3 years ago 176
Java Question

Trouble with 4D Array

Can someone please explain why I'm getting this error

Type mismatch: cannot convert from String to String[][][]


in this code?

String [][][][] names = {"zach","zach","zach","zach"};

Answer Source

The variable

String[][][][] names

is a variable representing a four-dimensional array of strings - that is, an array of arrays of arrays of arrays of strings. The literal

{"zach","zach","zach","zach"};

Is a single-dimensional string array with four elements in it. Notice the distinction - an array of four elements is a String[], not a String[][][][]. A one-dimensional array can have as many elements in it as you'd like. Adding more dimensions to the array is useful if you want to represent something like a 2D or 3D grid, but it's not the right way to say that the array holds more elements.

To fix this, you want to write

String[] names = {"zach","zach","zach","zach"};

This does indeed work correctly.

If you want a 2D array of strings, you could do something like this:

String[][] nameGrid = {
                         {"Alice", "Bob", "Charlie"},
                         {"David", "Eliza", "Fred"},
                         {"Gary", "Helen", "Isaac"},
                      };

Here, the data is two-dimensional - you select which row you'd like as the first array index, and which column you'd like as the second array index. Notice how the number of array elements in each row and column is independent of the number of dimensions in the array, since these are separate concepts.

Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download