12.1 T w o - Dimensional Arrays | 585
int[][] hits = {{2, 1, 0, 3, 2},
{1, 1, 2, 3, 4},
{1, 0},
{0, 1, 2, 1, 1}};
The third row in the table would have only two columns, not five like the others. In such a
ragged array, the lengths of the rows are not all the same. In fact, we could instantiate the same
ragged array as follows:
int[][] hits;
hits = new int[4][];
hits[0] = new int[5];
hits[1] = new int[5];
hits[2] = new int[2];
hits[3] = new int[5];
If we then access the lengths of rows 1 and 2 with the code
one = hits[1].length;
two = hits[2].length;
we would find that variable onehas been assigned a value of 5 and variable twocontains 2.
The moral here is that in Java, each row of a two-dimensional array is itself a one-di-
mensional array. Many programming languages directly support two-dimensional arrays; Java
doesn’t. In Java, a two-dimensional array is an array of references to array objects. Because
of the way that Java handles two-dimensional arrays, the drawings in Figures 12.1 and 12.2
are not quite accurate. Figure 12.3 shows how Java actually implements the array hiTemp.
hiTemp
[ 0 ]
[ 0 ]
[ 1 ]
[ 2 ]
[ 51 ]
[ 1 ][ 2 ][ 6 ]
Figure 12.3 Java Implementation of hiTempArray