tags:

views:

435

answers:

10

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

+2  A: 

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

Gopi
In fact, the enhanced for loop might be slower little a bit in many cases. But it is ignorable.
Dennis Cheung
Ohh I didnt know that. Just curious in what case .. any pointers/references?
Gopi
It was my understanding (but I could be wrong) that the enhanced for loop compiled to the same byte code as the regular for loop. If that is correct, then run-time behaviour should be identical.
emory
+8  A: 

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){
  ....
}
Sylvain M
You need to also add a line doing the extraction of the value. The advantage is that it eliminates a lot of simple boilerplate and any errors therein. After all, there's a great amount of code which just does iteration over collections in one way or another.
Donal Fellows
What is 'lisibility'?
EJP
"lisability" is franglais for "readability"
Axel
@EJP and Axel: oops, thank you...
Sylvain M
+2  A: 

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.

injekt
lol, nice inline comments!
Dimitris Andreou
A: 

As others already answer, it is a syntax sugar for cleaner. If you compare to the class Iterator loop, you will found one less variable you will have to declare.

Dennis Cheung
+1  A: 

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.

Zaki
+1  A: 

It is more concise. Only problem is null checking.

for (String str : strs) {  // make sure strs is not null here
    // Do whatever
}
fastcodejava
Why is that a problem?
EJP
It's certainly not necessarily a problem: I can have a list or array of objects that has nulls at some indices, and I'd hate to be unable to iterate over them. If I don't like a null, I can do this too: `if (str==null) continue;`
Donal Fellows
A: 

Less typing! Plus more help from the compiler

Thorbjørn Ravn Andersen
+1  A: 

As others said, the enhanced for loop provides cleaner syntax, readable code and less type.

Plus, it avoids the possible 'index out of bound' error scenario too. For example, when you iterate a list manually, you might use the index variable in a wrong way, like:

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

which will throw exception. But incase of enhanced for loop, we are leaving the iterating task to the compiler. It completely avoids the error case.

Veera
+7  A: 

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

Pascal Thivent
That's a nice proposal. Reminds me of [`LoopTagStatus`](http://download.oracle.com/docs/cd/E17410_01/javaee/6/api/javax/servlet/jsp/jstl/core/LoopTagStatus.html) which already exist for ages in JSTL `c:forEach`.
BalusC
@BalusC: Yes, indeed, I can see the similarities. And I also think that it's a nice proposal. But I didn't check the exact status, not sure it will be included.
Pascal Thivent
A: 

A foreach/enhanced for/for loop serves to provide a cursor onto a data object. This is particularly useful when you think in terms of “walk a file line by line” or “walk a result set record by record” as it is simple and straightforward to implement.

This also provides a more general and improved way of iterating compared to index-based methods because there is no longer any need for the caller (for loop) to know how values are fetched or collection sizes or other implementation details.