Java Reference
In-Depth Information
Imagine that you want to use a multidimensional array to represent a multiplication
table:
int
[][]
products
;
// A multiplication table
Each of the pairs of square brackets represents one dimension, so this is a two-
dimensional array. To access a single
int
element of this two-dimensional array, you
must specify two index values, one for each dimension. Assuming that this array
was actually initialized as a multiplication table, the
int
value stored at any given
element would be the product of the two indexes. That is,
products[2][4]
would
be 8, and
products[3][7]
would be 21.
a
x
To create a new multidimensional array, use the
new
keyword and specify the size of
both dimensions of the array. For example:
int
[][]
products
=
new
int
[
10
][
10
];
In some languages, an array like this would be created as a single block of 100
int
values. Java does not work this way. This line of code does three things:
• Declares a variable named
products
to hold an array of arrays of
int
.
• Creates a 10-element array to hold 10 arrays of
int
.
• Creates 10 more arrays, each of which is a 10-element array of
int
. It assigns
each of these 10 new arrays to the elements of the initial array. The default
value of every
int
element of each of these 10 new arrays is 0.
To put this another way, the previous single line of code is equivalent to the follow‐
ing code:
int
[][]
products
=
new
int
[
10
][];
// An array to hold 10 int[] values
for
(
int
i
=
0
;
i
<
10
;
i
++)
// Loop 10 times...
products
[
i
]
=
new
int
[
10
];
// ...and create 10 arrays
The
new
keyword performs this additional initialization automatically for you. It
works with arrays with more than two dimensions as well:
float
[][][]
globalTemperatureData
=
new
float
[
360
][
180
][
100
];
When using
new
with multidimensional arrays, you do not have to specify a size for
all dimensions of the array, only the leftmost dimension or dimensions. For exam‐
ple, the following two lines are legal:
float
[][][]
globalTemperatureData
=
new
float
[
360
][][];
float
[][][]
globalTemperatureData
=
new
float
[
360
][
180
][];
The first line creates a single-dimensional array, where each element of the array can
hold a
float[][]
. The second line creates a two-dimensional array, where each ele‐
ment of the array is a
float[]
. If you specify a size for only some of the dimensions
of an array, however, those dimensions must be the leftmost ones. The following
lines are not legal: