简体   繁体   English

Java中增强的for循环和迭代器有什么优势?

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

我想知道 Java +5 中增强的 for 循环和迭代器的优点是什么?

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:在 Stephen Colebourne(Joda-Time、JSR-310 等)中很好地总结了优点和缺点, 增强了每个循环迭代控制提案,以便在 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.扩展 Java 5 for-each 循环以允许访问循环索引,无论这是第一次还是最后一次迭代,并删除当前项。

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. for-each 循环几乎可以肯定是 Java 5 中最流行的新特性。它之所以有效,是因为它增加了抽象级别——而不是必须表达如何围绕列表或数组循环的低级细节(使用索引或迭代器),开发人员只需声明他们想要循环,语言会负责其余的工作。 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.每项工作的原始 Java 5 在旨在解决 80% 情况的许多问题上都采取了相对保守的立场。 However, loops are such a common form in coding that the remaining 20% that was not tackled represents a significant body of code.然而,循环是编码中的一种常见形式,剩下的 20% 未被处理代表了大量代码。

The process of converting the loop back from the for each to be index or iterator based is painful.将循环从 for each 转换回基于索引或迭代器的过程是痛苦的。 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'.这也很痛苦,因为大多数 IDE 不支持这种“解重构”。

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.总而言之,增强的 for 循环提供了一种简洁的高级语法来循环列表或数组,从而提高了清晰度和可读性。 However, it misses some parts: allowing to access the index loop or to remove an item.但是,它遗漏了一些部分:允许访问索引循环或删除项目。

See also也可以看看

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.迭代器变量在每个循环中出现 3 次:这是两次出错的机会。 The for-each construct gets rid of the clutter and the opportunity for error. for-each 结构消除了混乱和出错的机会。

Exactly确切地

When you see the colon (:) read it as “in.”当您看到冒号 (:) 时,将其读作“in”。 The loop above reads as “for each TimerTask t in c.”上面的循环读作“对于 c 中的每个 TimerTask t”。 As you can see, the for-each construct combines beautifully with generics.如您所见,for-each 构造与泛型完美结合。 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 .请注意,如果您需要在迭代时删除元素,则需要使用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.您不能使用for(String s : myList)删除列表中的元素。
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.还要注意,遍历数组时,foreach(或增强的for)只能用来获取元素,不能修改数组中的元素。
For more info, seethis .有关详细信息,请参阅

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...这通常没问题,但在性能关键部分(例如在实时应用程序中,当它必须每秒运行数百次时),它可能会导致主要的 GC 干预......

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.正如其他人所说,增强的 for 循环提供了更清晰的语法、可读的代码和更少的类型。

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.但是在增强 for 循环的情况下,我们将迭代任务留给编译器。 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.如果你比较类迭代器循环,你会发现你需要声明的变量少了一个。

It is more concise.它更简洁。 Only problem is null checking.唯一的问题是空检查。

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

A foreach/enhanced for/for loop serves to provide a cursor onto a data object. foreach/增强的 for/for 循环用于在数据对象上提供光标。 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.与基于索引的方法相比,这也提供了一种更通用和改进的迭代方式,因为调用者(for 循环)不再需要知道如何获取值或集合大小或其他实现细节。

Less typing!少打字! Plus more help from the compiler加上来自编译器的更多帮助

The enhanced for-loop offers the following main advantage:增强的 for 循环具有以下主要优点:

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.它消除了上述非增强版本中每次迭代时list.size()的重复计算。 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++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM