ArrayBracketCountIsLengthDRAFT
To allocate an array, one specifies a []
for each element.
This has two consequences:
(1) The type of an array of three int
elements is int[][][]
.
(2) To allocate such an array one writes new int [5][6][7]
.
The number of brackets in an array type or an array initializer corresponds to the length of the array
The number of brackets in an array type or an array initializer corresponds to the rank of the array
CorrectionHere is what's right.
The square brackets []
stand for a dimension, not for an element.
The type int[][]
means a two-dimensional array of ints
(an array of arrays of ints).
The number of dimensions of an array is called the rank.
Moreover, in Java the type of an array is independent of the length of the array.
A one-dimensional array of three int
s (new int[3]
) has the same type
as a one-dimensional array of four int
s (new int[4]
).
SymptomsHow do you know your students might have this misconception?
Here is an example of this misconception occurring in the initializer:
int[] a = new int[1][2][3][4][5];
And here is an example in the type:
int[][][][][] a = new int[5];
And here is an example in both, the type and the initializer:
int[][][][][] a = new int[1][2][3][4][5];
Finally, here is the misconception surfacing in answers to a question about multi-dimensional arrays: How many arrays/objects are allocated by the following expression?
new Pacman[2][4]
One answer stated that this expression allocated two arrays, one with length 2, and one with length 4. Another answer stated that it allocated two arrays, one for x and one for y.