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

can anyone please specify to me what are the advantages of Enhanced for loop and Iterators in java +5 ?


Solution 1:

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

  • Java 7 - For-each loop control access
  • Stephen Colebourne's original writeup

Solution 2:

For me, it's clear, the main advantage is readability.

for(Integer i : list){
   ....
}

is clearly better than something like

for(int i=0; i < list.size(); ++i){
  ....
}

Solution 3:

I think it's pretty much summed up by the documentation page introducing it here.

Iterating over a collection is uglier than it needs to be

So true..

The iterator is just clutter. Furthermore, it is an opportunity for error. The iterator variable occurs three times in each loop: that is two chances to get it wrong. The for-each construct gets rid of the clutter and the opportunity for error.

Exactly

When you see the colon (:) read it as “in.” The loop above reads as “for each TimerTask t in c.” As you can see, the for-each construct combines beautifully with generics. It preserves all of the type safety, while removing the remaining clutter. Because you don't have to declare the iterator, you don't have to provide a generic declaration for it. (The compiler does this for you behind your back, but you need not concern yourself with it.)

I'd like to sum it up more, but I think that page does it pretty much perfectly.

Solution 4:

You can iterate over any collection that's Iterable and also arrays. And the performance difference isn't anything you should be worried about at all.

Readability is important.

Prefer this    
for (String s : listofStrings) 
    {
     ... 
    }

over

    for (Iterator<String> iter = listofStrings.iterator(); iter.hasNext(); )
    {
     String s = iter.next();
     ...
    }

Note that if you need to delete elements as you iterate, you need to use Iterator.

For example,

List<String> list = getMyListofStrings(); 

    for (Iterator<String> iter = list.iterator(); iter.hasNext(); ) 
    {
        String s = iter.next();
        if (someCondition) {
            iter.remove(); 
        }
    }

You can't use for(String s : myList) to delete an element in the list.
Also note that when iterating through an array, foreach (or enhanced for) can be used only to obtain the elements, you can't modify the elements in the array.
For more info, see this.

Solution 5:

A cleaner syntax ! There is no difference from the performance perspective as this is just a convenience for a programmer.