Java Reference
In-Depth Information
Multidimensional arrays with two dimensions are often used to represent
tables
of values
with data arranged in
rows
and
columns
. To identify a particular table element, you specify
two
indices.
By convention
, the first identifies the element's row and the second its column.
Arrays that require two indices to identify each element are called
two-dimensional arrays
.
(Multidimensional arrays can have more than two dimensions.) Java does not support mul-
tidimensional arrays directly, but it allows you to specify one-dimensional arrays whose ele-
ments are also one-dimensional arrays, thus achieving the same effect. Figure 7.16 illustrates
a two-dimensional array named
a
with three rows and four columns (i.e., a three-by-four ar-
ray). In general, an array with
m
rows and
n
columns is called an
m
-by-
n
array
.
Column 0
Column 1
Column 2
Column 3
Row 0
a[ 0 ][ 0 ]
a[ 0 ][ 1 ]
a[ 0 ][ 2 ]
a[ 0 ][ 3 ]
Row 1
a[ 1 ][ 0 ]
a[ 1 ][ 1 ]
a[ 1 ][ 2 ]
a[ 1 ][ 3 ]
Row 2
a[ 2 ][ 0 ]
a[ 2 ][ 1 ]
a[ 2 ][ 2 ]
a[ 2 ][ 3 ]
Column index
Row index
Array name
Fig. 7.16
|
Two-dimensional array with three rows and four columns.
Every element in array
a
is identified in Fig. 7.16 by an
array-access expression
of the form
a[
row
][
column
]
;
a
is the name of the array, and
row
and
column
are the indices that uniquely
identify each element by row and column index. The names of the elements in
row
0 all have
a
first
index of
0
, and the names of the elements in
column
3 all have a
second
index of
3
.
Arrays of One-Dimensional Arrays
Like one-dimensional arrays, multidimensional arrays can be initialized with array initial-
izers in declarations. A two-dimensional array
b
with two rows and two columns could be
declared and initialized with
nested array initializers
as follows:
int
[][] b = {{
1
,
2
}, {
3
,
4
}};
The initial values are
grouped by row
in braces. So
1
and
2
initialize
b[0][0]
and
b[0][1]
,
respectively, and
3
and
4
initialize
b[1][0]
and
b[1][1]
, respectively. The compiler
counts the number of nested array initializers (represented by sets of braces within the out-
er braces) to determine the number of
rows
in array
b
. The compiler counts the initializer
values in the nested array initializer for a row to determine the number of
columns
in that
row. As we'll see momentarily, this means that
rows can have different lengths
.
Multidimensional arrays are maintained as
arrays of one-dimensional arrays
. Therefore
array
b
in the preceding declaration is actually composed of two separate one-dimensional
arrays—one containing the values in the first nested initializer list
{1, 2}
and one con-
taining the values in the second nested initializer list
{3, 4}
. Thus, array
b
itself is an array
of two elements, each a one-dimensional array of
int
values.