Java Reference
In-Depth Information
Each row of matrix is a one-dimensional array; matrix[0] , in fact, refers to the first
row. Therefore, the value of the expression:
matrix[0].length
is 15 , the number of columns in the first row. Similarly, matrix[1].length gives the
number of columns in the second row, which in this case is 15 , and so on.
TWO-DIMENSIONAL ARRAYS: SPECIAL CASES
The two-dimensional arrays created in the preceding sections are quite straightforward;
each row has the same number of columns. However, Java allows you to specify a
different number of columns for each row. In this case, each row must be instantiated
separately. Consider the following statement:
int [][] board;
Suppose that you want to create the array board , as shown in Figure 9-18.
board
board[0]
board[1]
board[2]
board[3]
board[4]
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
9
0
0
0
FIGURE 9-18 Array board
It follows from Figure 9-18 that the number of rows in board is 5 , the number of
columns in the first row is 6 , the number of columns in the second row is 2 , the number
of columns in the third row is 5 , the number of columns in the fourth row is 3 , and the
number of columns in the fifth row is 4 . To create this two-dimensional array, first we
create the one-dimensional array board of 5 rows. Then, we instantiate each row,
specifying the required number of columns, as follows:
board = new int [5][];
//Create the number of rows
board[0] = new int [6]; //Create the columns for the first row
board[1] = new int [2]; //Create the columns for the second row
board[2] = new int [5]; //Create the columns for the third row
board[3] = new int [3]; //Create the columns for the fourth row
board[4] = new int [4]; //Create the columns for the fifth row
Because the number of columns in each row is not the same, such arrays are called
ragged arrays. To process these types of two-dimensional arrays, you must know the
exact number of columns for each row.
Search WWH ::




Custom Search