What are the advantages of Enhanced for loop and Iterator in Java?

The strengths and also the weaknesses are pretty well summarized in Stephen Colebourne (Joda-Time, JSR-310, etc) Enhanced for each loop iteration control proposal to extend it in Java 7:

FEATURE SUMMARY:

Extends the Java 5 for-each loop to allow access to the
loop index, whether this is the first
or last iteration, and to remove the
current item.

MAJOR ADVANTAGE

The for-each loop is almost certainly the most new
popular feature from Java 5. It works
because it increases the abstraction
level – instead of having to express
the low-level details of how to loop
around a list or array (with an index
or iterator), the developer simply
states that they want to loop and the
language takes care of the rest.
However, all the benefit is lost as
soon as the developer needs to access
the index or to remove an item
.

The original Java 5 for each work took
a relatively conservative stance on a
number of issues aiming to tackle the
80% case. However, loops are such a
common form in coding that the
remaining 20% that was not tackled
represents a significant body of code.

The process of converting the loop
back from the for each to be index or
iterator based is painful. This is
because the old loop style if
significantly lower-level, is more
verbose and less clear
. It is also
painful as most IDEs don’t support
this kind of ‘de-refactoring’.

MAJOR BENEFIT:

A common coding idiom is expressed at
a higher abstraction than at present.
This aids readability and clarity.

To sum up, the enhanced for loop offers a concise higher level syntax to loop over a list or array which improves clarity and readability. However, it misses some parts: allowing to access the index loop or to remove an item.

See also

Leave a Comment