迭代器与每次 [英] Iterator vs For-Each

查看:99
本文介绍了迭代器与每次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在SO上有很多类似的问题.但这似乎以前没有讨论过.

I know there are a lot of similar questions here on SO. But it seems this wasn't discussed before.

总的来说,我想知道,如果不删除任何元素,为什么应该在For-Each循环上使用Iterator?因此,基本上只是遍历Collection,而唯一使用的修饰符是add.

In general I want to know, why an Iterator should be used over a For-Each loop, if no element will be removed? So, basically just iterating over a Collection, and the only used modifier is add.

我知道,如果从Collection中删除元素,则Iterator是唯一的保存选项. 性能不是参数,因为For-Each将由编译器转换为Iterator. Iterator更冗长,因此+1到For-Each.

I'm aware that Iterator is the only save option if an element is removed from a Collection. Performance is no argument, because the For-Each will be transformed into an Iterator by the compiler. The Iterator is more verbose, so +1 to For-Each.

在上述情况下,是否有可靠的理由在For-Each上使用Iterator?

Is there any reliable point to use an Iterator over For-Each in the described scenario?

推荐答案

如果需要,您需要使用Iterator循环而不是foreach循环

You need to use an Iterator loop instead of a foreach loop if

  • 您需要能够在处理过程中删除项目,或者
  • 您需要对最后一项进行不同的处理.

此外,如果您希望能够根据前一个元素的特征来跳过该元素,则Iterator可能会更自然.

Also, an Iterator may be more natural if you want to be able to skip an element based on characteristics of its previous element.

另外,对于List来说,ListIterator循环有时可能比foreach循环更方便,因为它可以提供上一个和下一个元素的索引,并且(甚至除索引之外)还可以使您识别迭代的第一个元素.此外,您还需要ListIterator如果

Additionally, for Lists, a ListIterator loop may sometimes be more convenient than a foreach loop, as it can provide the indexes of the previous and next elements, and (even apart from the indexes) allows you to recognize the first element of the iteration. Furthermore, you need a ListIterator if

  • 您必须替换基础List中的元素,或
  • 您需要备份.
  • you have to replace elements in the underlying List, OR
  • you ever need to back up.

这篇关于迭代器与每次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆