Java Reference
In-Depth Information
To instantiate a multidimensional array, you denote the size of each dimension in the
new statement. For example:
7. values = new char[4][3];
8. names = new String[10][5][20];
To access an element in a multidimensional array, specify an index for each dimension.
For example, the following statement stores an 'A' in the fi rst column of the fi rst row of
values , and “George Washington” in the twentieth level of the second column of the fi rst
row of names :
9. values[0][0] = 'A';
10. names[0][1][19] = “George Washington”;
The following nested for loops are typical when working with two-dimensional arrays.
These particular nested loops fi ll the values array with chars starting with ' A '. (Similarly,
you could use three nested loops to iterate through the names array.)
11. char current = 'A';
12. for(int row = 0; row < values.length; row++) {
13. for(int col = 0; col < values[row].length; col++) {
14. values[row][col] = current++;
15. }
16. }
Figure 2.6 shows what the values array looks like in memory. The values array consists
of 4 arrays, each containing 3 chars for a total of 12 chars .
FIGURE 2.6 The values array is a double array of chars .
'A'
'B'
'C'
'D'
'E'
'F'
0
1
2
3
values
'G'
'H'
'I'
A char[][] reference
'J'
'K'
'L'
An array of four
char[] references
Four char arrays
Search WWH ::




Custom Search