Java Reference
In-Depth Information
Ragged Arrays
★
There is no need for each row in a two-dimensional array to have the same number of
entries. Different rows can have different numbers of columns. These sorts of arrays
are called
ragged arrays
.
To help explain the details, let's start with an ordinary, nonragged two-dimensional
array, created as follows:
ragged arrays
double
[][] a =
new double
[3][5];
This is equivalent to the following:
double
[][] a;
a =
new double
[3][];
a[0] =
new double
[5];
a[1] =
new double
[5];
a[2] =
new double
[5];
The line
a =
new double
[3][];
makes
a
the name of an array with room for three entries, each of which can be an
array of
double
s that can be of any length. The next three lines each create an array of
double
s of length
5
to be named by
a[0]
,
a[1]
, and
a[2]
. The net result is a two-
dimensional array of base type
double
with three rows and five columns.
If you want, you can make each of
a[0]
,
a[1]
, and
a[2]
a different length. The fol-
lowing code makes a ragged array
b
in which each row has a different length:
double
[][] b;
b =
new double
[3][];
b[0] =
new double
[5];
b[1] =
new double
[10];
b[2] =
new double
[4];
There are situations in which you can profitably use ragged arrays, but most appli-
cations do not require them. However, if you understand ragged arrays, you will have a
better understanding of how all multidimensional arrays work in Java.
Multidimensional Array Parameters and Returned Values
Methods may have multidimensional array parameters and may have a multidimen-
sional array type as the type for the value returned. The situation is similar to that of
the one-dimensional case, except that you use more square brackets when specifying
array
arguments