Java Reference
In-Depth Information
For example, suppose
x = new int[3][4]
,
x[0]
,
x[1]
, and
x[2]
are one-dimensional
arrays and each contains four elements, as shown in Figure 7.2.
x.length
is
3
, and
x[0].length
,
x[1].length
, and
x[2].length
are
4
.
x
x[0][0] x[0][1]
x[0][2]
x[0][3]
x[0].length
is
4
x[0]
x[1]
x[1][0] x[1][1] x[1][2] x[1][3]
x[1].length
is
4
x[2]
x[2][0] x[2][1] x[2][2] x[2][3]
x[2].length
is
4
x.length
is
3
F
IGURE
7.2
A two-dimensional array is a one-dimensional array in which each element is
another one-dimensional array.
7.2.3 Ragged Arrays
Each row in a two-dimensional array is itself an array. Thus, the rows can have different
lengths. An array of this kind is known as a
ragged array
. Here is an example of creating a
ragged array:
ragged array
int
[][] triangleArray = {
{
1
,
2
,
3
,
4
,
5
},
{
2
,
3
,
4
,
5
},
{
3
,
4
,
5
},
{
4
,
5
},
{
5
}
};
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
As you can see,
triangleArray[0].length
is 5,
triangleArray[1].length
is 4,
triangleArray[2].length
is 3,
triangleArray[3].length
is 2, and
triangle-Array[4].length
is 1.
If you don't know the values in a ragged array in advance, but do know the sizes—say, the
same as before—you can create a ragged array using the following syntax:
int
[][] triangleArray =
new int
[
5
][]
;
triangleArray[
0
] =
new int
[
5
];
triangleArray[
1
] =
new int
[
4
];
triangleArray[
2
] =
new int
[
3
];
triangleArray[
3
] =
new int
[
2
];
triangleArray[
4
] =
new int
[
1
];
You can now assign values to the array. For example,
triangleArray[
0
][
3
] =
50
;
triangleArray[
4
][
0
] =
45
;
Note
The syntax
new int[5][]
for creating an array requires the first index to be specified.
The syntax
new int[][]
would be wrong.
✓
✓
Check
Point
7.1
Declare an array reference variable for a two-dimensional array of
int
values, create
a 4-by-5
int
matrix, and assign it to the variable.