Java Reference
In-Depth Information
}
The effect of this is to produce the array layout that is shown in Figure 4-5 .
FIGURE 4-5
The 21 elements in the array occupy 84 bytes. When you need a two-dimensional array with rows of
varying length, allocating them to fit the requirement can save a considerable amount of memory compared
to just using rectangular arrays where the row lengths are all the same.
To check out that the array is as shown in Figure 4-5 , you can define it in a program using the code frag-
ments you have just seen and include statements to display the length member for each of the one-dimen-
sional arrays.
You could use a numerical for loop to initialize the elements in the samples array, even though the rows
may differ in length:
for(int i = 0; i < samples.length; ++i) {
for(int j = 0 ; j < samples[i].length ; ++j) {
samples[i][j] = 99.0f; // Initialize each element to 99
}
}
Of course, for the loops to execute properly the arrays must already have been created. The upper limit
for the control variable in the inner loop is samples[i].length . The expression samples[i] references the
current row in the two-dimensional array so samples[i].length is the number of elements in the current
row. The outer loop iterates over the rows in the samples array, and the inner loop iterates over all the ele-
ments in a row.
 
 
Search WWH ::




Custom Search