Java Reference
In-Depth Information
TABLE 5 . 1 : Example
two-dimensional array.
0 1 2 3
4
5
6
7 8 9
0
1
2
3
X X X X
4
5
6
7
8
9
location 1000
table = 1000
FIGURE 5.5: Initial array.
board[3][4]= true ;
board[3][5]= true ;
board[3][6]= true ;
Here is the place to discuss that Java does not have a native support for two-dimensional
arrays. In fact, it stores a two-dimensional array as an array of one-dimensional arrays. In
order to demonstrate this point, consider the following code.
int [][] table = new i n t [3][];
for ( int row = 0; row < = 2 ; row ++) {
table [row] = new i n t [row +1];
for ( int col = 0; col < row+1 ;
c o l ++) {
table [row][ col]=col+1;
}
}
The first line creates an array of 3 elements, where every element is an array of integers.
Pictorially, this can be represented as shown in Figure 5.5. The three elements of the array
will be initially empty. After the code segment is executed, the array will now look as shown
in Figure 5.6. For example, when row=0 , a one-dimensional array is created and the first
element of the table array is directed to point to it.
A two-dimensional array in Java is implemented as an array of arrays. When the
first array contains arrays of different sizes, the array is called ragged .
An array in which rows have different lengths is called a ragged array . The advantage of
using a ragged array is that it saves space. Without doubt, knowing how to create ragged
arrays is one reason for understanding the internals of how a two-dimensional array is
created in Java. Another advantage of knowing how a two-dimensional array is stored is
 
Search WWH ::




Custom Search