Reputation: 1361
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"};
Upvotes: 1
Views: 1600
Reputation: 372982
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!
Upvotes: 5
Reputation: 11
If you want a 1D array;
String[] names = {"zach","zach","zach","zach"};
If you want a 4D array;
// Only filling one dimension of the 4D array
String [][][][] names = {{{{"zach","zach","zach","zach"}}}};
Reference; http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx
Upvotes: 0