The improved version of the for
also runs on multidimensional arrays. Recognize, yet, that in Java, multidimensional arrays consist of arrays of arrays
. (For instance, a two-dimensional array is an array of one-dimensional arrays.)
Iterating Over Multidimensional Arrays
This is necessary when iterating over a multidimensional array, as each iteration obtains the next array, not an individual element. Moreover, the iteration variable in the for
loop must be compatible with the type of array being obtained.
For instance, in the case of a two-dimensional array, the iteration variable must be a reference to a one-dimensional array. In common, when using the for-each
for
to iterate over an array of N
dimensions, the objects obtained will be arrays of N–1
dimensions. To get the implications of this, analyze the following program. It makes use nested for
loops to obtain the elements of a two-dimensional array in a row-order, from beginning to end.
// Use for-each style for on a two-dimensional array. class ForEach3 { public static void main(String args[]) { int sum = 0; int nums[][] = new int[3][5]; // give nums some values for(int i = 0; i < 3; i++) for(int j = 0; j < 5; j++) nums[i][j] = (i+1)*(j+1); // use for-each for to display and sum the values for(int x[] : nums) { for(int y : x) { System.out.println("Value is: " + y); sum += y; } } System.out.println("Summation: " + sum); } }
The output from this program is shown here: Value is: 1 Value is: 2 Value is: 3 Value is: 4 Value is: 5 Value is: 2 Value is: 4 Value is: 6 Value is: 8 Value is: 10 Value is: 3 Value is: 6 Value is: 9 Value is: 12 Value is: 15 Summation: 90
In the program, give special attention to this line:
for(int x[]: nums) {
See how x
is declared. It is a reference to a one-dimensional array of integers. This is essential as each iteration of the for obtaining the next array in nums, starting with the array specified by nums[0]
. The inner for
loop then cycles within each of these arrays, displaying the values of each element.
Applying the Enhanced for
Since the for-each
style for can only cycle within an array in sequential order, from start to end, you might think that its use is bound, but this is not true.
A large number of algorithms need precisely this mechanism. One of the most basic is searching. For instance, the following program uses a for loop to search an unsorted array for a value. It stops if the value is found.
// Search an array using for-each style for. class Search { public static void main(String args[]) { int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 }; int val = 5; boolean found = false; // use for-each style for to search nums for val for(int x : nums) { if(x == val) { found = true; break; } } if(found) System.out.println("Value found!"); } }
The for-each
style for
is an outstanding choice in this application because searching an unsorted array requires examining each element in a sequence.