We will cover the usage of Enhanced for-loop in this section. This is also referred to as for-each loop. The following code shows how to iterate over the elements in a Collection using the traditionalForEachTest.java
Though the goal of the above program is traversing over the elements in the list collection, we are depending on the
IteratorAPI to achieve this. A replacement to the Iterator is the usage of Enhanced for-loop, through which it is possible to have a short and a neat code like this,
Let us see how the above syntax is used to traverse over the collection. The expression before the symbol
':'is a declaration statement which declares an
Integerobject called number for holding the individual element from the collection. The expression that follows after the symbol must be a Collection type whose elements can be iterated. Precisely, this type must implement an interface called
java.util.Iterablewhich has a single method called
iterator(). During compile-time, the compiler translates the above code which looks very similar to the following,
Even it is possible to apply this new syntax for type Arrays. So, the following code is perfectly legal and it compiles fine.
The enhanced for-loop is just a convenience from the programmer's point of view for iterating over the Collection. But the usage of this loop has some dis-advantages. The first one out of the two is that step-value cannot be incremented. For example, it is not possible to traverse the first element and then the thirth element and so on. And the second dis-advantage is that backward traversal is not possible.