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:
No comments:
Post a Comment
If you have any query please comment here, Will get back to you :)