Radith said:
The NetBeans compiler will not let me initialize a 3D array in the following
way:
int[][][] a2 = {
{ 1, 2, 3, },
{ 4, 5, 6, },
{ 7, 8, 9, },
};
The initializer is only 2D.
WHAT IS THE CORRECT METHOD TO DO THIS?
WHAT DO YOU MEAN BY "THIS?" (Oh, sorry; I shouldn't
shout at people.)
You could write
int[][][] a2 = { {
{ 1, 2, 3, },
{ 4, 5, 6, },
{ 7, 8, 9, },
}, };
.... but that would be rather pointless: You'd have a 3D
array, but the first dimension would have only one index.
(Roughly speaking, you'd have a "[1][3][3]" array.)
Here's a suggestion: Each pair of [brackets] in the
array dimensions matches up with one level of {braces} in
the initializer, so give each brace level its own level
of indentation:
int[][][] a2 =
{
{
{ 1, 2, 3, },
{ 4, 5, 6, },
{ 7, 8, 9, },
},
{
{ 3, 1, 4, },
{ 1, 5, 9, },
},
{
{ 2, 7, 1, 8, },
{ 2, 8, 1, },
{ 8, 2, 4, 5, 9, 0, 5, },
},
};
You may eventually decide to adopt a more compressed
style, but a scheme like this may help you keep your wits
about you while your confidence grows.
Note that the sample above creates a "ragged" array.
The ability to have such things is a consequence of the
fact that Java really doesn't have multi-dimensional arrays
at all. It does, however, have singly-dimensioned arrays
whose elements can themselves be singly-dimensioned arrays,
and the elements of *those* can be singly-dimensioned arrays,
and so on:
a2 is an array with three elements, all arrays
a2[0] is an array with three elements, all arrays
a2[0][0] is an array with three `int' elements
... as are a2[0][1] and a2[0][2]
a2[1] is an array with two elements, both arrays
a2[1][0] is an array with three `int' elements
... as is a2[1][1]
a2[2] is an array with three elements, all arrays
a2[2][0] is an array with four `int' elements
a2[2][1] is an array with three `int' elements
a2[2][2] is an array with seven `int' elements
If you ponder this for a while, you'll see why the
"complete brace style" is a necessity in Java: there is
no way Java can infer where the level transitions occur
by counting elements or any such.