开发者

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

开发者 https://www.devze.com 2023-01-08 13:54 出处:网络
I would like to know what are the advantages of Enhanced for loop and Iterators in 开发者_运维知识库Java +5 ?The strengths and also the weaknesses are pretty well summarized inStephen Colebourne (Joda

I would like to know what are the advantages of Enhanced for loop and Iterators in 开发者_运维知识库Java +5 ?


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


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){
  ....
}


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.


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.


Major drawback is the creation of an Iterator, which is not there with an index-based loop. It is usually OK, but in performance-critical sections (in a real-time application for instance, when it has to run several hundreds times a second), it can cause major GC intervention...


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


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.


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.


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.


It is more concise. Only problem is null checking.

for (String str : strs) {  // make sure strs is not null here
    // Do whatever
}


Less typing! Plus more help from the compiler


The enhanced for-loop offers the following main advantage:

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

It eliminates the repeated calculation of list.size() on every iteration in the non-enhanced version above. This is a performance advantage that matters.

Alternatively, you may calculate the size outside the loop as follows using an additional variable:

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

精彩评论

暂无评论...
验证码 换一张
取 消