Java Reference
In-Depth Information
or
int matrix[][]; // This style is allowed, but not preferred
You can create a two-dimensional array of 5-by-5 int values and assign it to matrix
using this syntax:
matrix = new int [ 5 ][ 5 ];
Two subscripts are used in a two-dimensional array, one for the row and the other for the
column. As in a one-dimensional array, the index for each subscript is of the int type and
starts from 0 , as shown in Figure 8.1a.
[0]
[1]
[2]
[3]
[4]
[0]
[1]
[2]
[3]
[4]
[0]
[1]
[2]
[0]
0
0
0
0
0
[0]
0
0
0
0
0
[0] 1
23
456
789
10 11 12
[1]
0
0
0
0
0
[1]
0
0
0
0
0
[1]
[2]
0
0
0
0
0
[2]
0
7
0
0
0
[2]
[3]
0
0
0
0
0
[3]
0
0
0
0
0
[3]
[4]
0
0
0
0
0
[4]
0
0
0
0
0
int [][] array = {
{ 1 , 2 , 3 },
{ 4 , 5 , 6 },
{ 7 , 8 , 9 },
{ 10 , 11 , 12 }
matrix = new int [ 5 ][ 5 ];
matrix[ 2 ][ 1 ] = 7 ;
};
(a)
(b)
(c)
F IGURE 8.1
The index of each subscript of a two-dimensional array is an int value,
starting from 0 .
To assign the value 7 to a specific element at row 2 and column 1 , as shown in Figure 8.1b,
you can use the following syntax:
matrix[ 2 ][ 1 ] = 7 ;
Caution
It is a common mistake to use matrix[2, 1] to access the element at row 2 and
column 1 . In Java, each subscript must be enclosed in a pair of square brackets.
You can also use an array initializer to declare, create, and initialize a two-dimensional
array. For example, the following code in (a) creates an array with the specified initial values,
as shown in Figure 8.1c. This is equivalent to the code in (b).
int [][] array = {
{ 1 , 2 , 3 },
{ 4 , 5 , 6 },
{ 7 , 8 , 9 },
{ 10 , 11 , 12 }
};
int [][] array = new int [ 4 ][ 3 ];
array[ 0 ][ 0 ] = 1 ; array[ 0 ][ 1 ] = 2 ; array[ 0 ][ 2 ] = 3 ;
array[ 1 ][ 0 ] = 4 ; array[ 1 ][ 1 ] = 5 ; array[ 1 ][ 2 ] = 6 ;
array[ 2 ][ 0 ] = 7 ; array[ 2 ][ 1 ] = 8 ; array[ 2 ][ 2 ] = 9 ;
array[ 3 ][ 0 ] = 10 ; array[ 3 ][ 1 ] = 11 ; array[ 3 ][ 2 ] = 12 ;
Equivalent
(a)
(b)
8.2.2 Obtaining the Lengths of Two-Dimensional Arrays
A two-dimensional array is actually an array in which each element is a one-dimensional
array. The length of an array x is the number of elements in the array, which can be obtained
using x.length . x[0] , x[1] , . . . , and x[x.length-1] are arrays. Their lengths can be
obtained using x[0].length , x[1].length , . . . , and x[x.length-1].length .
 
 
Search WWH ::




Custom Search