Java Reference
In-Depth Information
Iterating Over Multidimensional Arrays
The enhanced for also works on multidimensional arrays. Remember, however, that in
Java, multidimensional arrays consist of arrays of arrays . (For example, a two-dimensional
array is an array of one-dimensional arrays.) This is important when iterating over a multi-
dimensional array because each iteration obtains the next array , not an individual element.
Furthermore, the iteration variable in the for loop must be compatible with the type of array
being obtained. For example, in the case of a two-dimensional array, the iteration variable
must be a reference to a one-dimensional array. In general, when using the for-each for to
iterate over an array of N dimensions, the objects obtained will be arrays of N -1 dimen-
sions. To understand the implications of this, consider the following program. It uses nested
for loops to obtain the elements of a two-dimensional array in row order, from first to last.
The output from this program is shown here:
Search WWH ::




Custom Search