Enhanced for Loops

Programmers frequently want to traverse a collection and visit each element for some processing. While an iterator can be used to do this, Java 5.0 provides some "syntactic sugar" for an iterator-based loop, in the form of an enhanced for loop. The following code segment shows the use of such a loop with a collection of strings:

for (String str : col){
   // Do something with str
}

Like an iterator, an enhanced for loop relieves the programmer of the need to initialize, test, and update an index variable (when used with indexed collections). In our example, the variable str assumes the value of each element in the collection during the traversal. The scope of str is the body of the loop. The collection col can be any collection that implements the Iterable interface, including Java's built-in arrays, lists, sets, stacks, queues, priority queues, and many programmer-defined collections (see our TrueStack resource) .

 

The syntax of the enhanced for loop is simpler and more fool-proof than that of the iterator-based loop. However, the enhanced for loop does have several major limitations: