Monday, September 28, 2015

The For-Each Loop Version of the For Loop

Beginning with JDK 5 A second form of for was defined that implements a “for-each” style loop. A foreach style loop is designed to cycle through a collection of objects such as an array in strictly sequential fashion from start to finish.
The advantage of this approach is that no new keyword is required and no preexisting code is broken. The for-each style of for is also referred to as the enhanced for loop.
The general form of the for-each version of the for is shown here:
for(type itr-var : collection)
statement-block
Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the elements from acollection. one at a time, from beginning to end.
The collection being cycled through is specified by collection. There are various types of collections that can be used with the for.
With each iteration of the loop, the next element in the collection is retrieved and stored in itr-var. The loop repeats until all elements in the collection have been obtained. Because the iteration variable receives values from the collection.
Type must be the same as (or compatible with) the elements stored in the collection. Thus, when iterating over arrays, type must be compatible with the base type of the array.
To understand the motivation behind a for-each style loop, consider the type of for loop that it is designed to replace. The following fragment uses a traditional for loop to compute the sum of the values in an array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Using Simple For Loop.
class WLFor
{
public static void main(String args[])
{
int nums[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int sum = 0;
for(int i=0; i < 10; i++)
{
sum += nums[i];
}
System.out.println(sum);
}
}
To compute the sum, each element in nums is read, in order, from start to finish. Thus, the entire array is read in strictly sequential order. This is accomplished by manually indexing the nums array by i, the loop control variable.
The for-each style for automates the preceding loop. Specifically, it eliminates the need to establish a loop counter, specify a starting and ending value and manually index the array. Instead it automatically cycles through the entire array obtaining one element at a time in sequence from beginning to end.
For example, here is the preceding fragment rewritten using a for-each version of the for:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Using For-Each Loop.
class WLForEach
{
public static void main(String args[])
{
int nums[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int sum = 0;
for(int x: nums)
{
sum += x;
}
System.out.println(sum);
}
}