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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3328672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:12:11  来源:igfitidea点击:

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

javaforeach

提问by Mahmoud Saleh

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

任何人都可以向我指定 java +5 中增强的 for 循环和迭代器的优点是什么?

采纳答案by Pascal Thivent

The strengths and also the weaknesses are pretty well summarized in Stephen Colebourne (Joda-Time, JSR-310, etc) Enhanced for each loop iteration controlproposal 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.

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 styleif 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.

...

功能摘要:

扩展 Java 5 for-each 循环以允许访问循环索引,无论这是第一次还是最后一次迭代,并删除当前项。

主要优势

for-each 循环几乎可以肯定是 Java 5 中最流行的新特性。它之所以有效是因为它提高了抽象级别——而不是必须表达如何循环列表或数组的低级细节(使用索引或迭代器),开发人员只是声明他们想要循环,剩下的由语言来处理。但是,一旦开发人员需要访问索引或删除项目,所有好处都将丢失

每项工作的原始 Java 5 在一些旨在解决 80% 情况的问题上采取了相对保守的立场。然而,循环是编码中的一种常见形式,剩下的 20% 没有被解决,代表了一个重要的代码体。

将循环从 for each 转换回基于索引或迭代器的过程是痛苦的。这是因为旧的循环样式如果明显较低级别,则更冗长且不太清晰。这也很痛苦,因为大多数 IDE 不支持这种“去重构”。

主要优点:

一种通用的编码习惯用法比目前的抽象化程度更高。这有助于可读性和清晰度

...

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.

总而言之,增强的 for 循环提供了一种简洁的高级语法来循环列表或数组,从而提高了清晰度和可读性。但是,它遗漏了一些部分:允许访问索引循环或删除项目。

See also

也可以看看

回答by Gopi

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

更简洁的语法!从性能角度来看没有区别,因为这只是为了程序员的方便。

回答by sly7_7

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

回答by Lee Jarvis

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.

迭代器只是混乱。此外,这是一个出错的机会。迭代器变量在每个循环中出现 3 次:这是两次出错的机会。for-each 结构消除了混乱和出错的机会。

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

当您看到冒号 (:) 时,将其读为“in”。上面的循环读作“对于 c 中的每个 TimerTask t”。如您所见,for-each 构造与泛型完美结合。它保留了所有类型安全性,同时消除了剩余的混乱。因为您不必声明迭代器,所以不必为其提供通用声明。(编译器会在背后为你做这件事,但你不必关心它。)

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

我想对其进行更多总结,但我认为该页面做得非常完美。

回答by Dennis C

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.

正如其他人已经回答的那样,它是更清洁的语法糖。如果与类 Iterator 循环进行比较,您会发现少了一个必须声明的变量。

回答by Zaki

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.

您可以迭代任何可迭代的集合以及数组。性能差异根本不是您应该担心的。

Readabilityis 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.
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.

您不能使用for(String s : myList)删除列表中的元素。
还要注意,在遍历数组时,foreach(或增强for)只能用于获取元素,不能修改数组中的元素。
有关更多信息,请参阅

回答by fastcodejava

It is more concise. Only problem is null checking.

它更简洁。唯一的问题是空检查。

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

回答by Thorbj?rn Ravn Andersen

Less typing! Plus more help from the compiler

少打字!加上来自编译器的更多帮助

回答by Veera

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. It completely avoids the error case.

这将抛出异常。但是在增强 for 循环的情况下,我们将迭代任务留给编译器。它完全避免了错误情况。

回答by user268396

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.

foreach/enhanced for/for 循环用于在数据对象上提供游标。当您考虑“逐行遍历文件”或“逐条记录遍历结果集”时,这特别有用,因为它实现起来简单明了。

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 循环)不再需要知道如何获取值或集合大小或其他实现细节。