简体   繁体   English

for-each和for循环

[英]for-each and for loops

Several times I have come across cases where the for-each loop would cause problems, including exceptions and crashes, while the for(it=list.iterator;it.hasNext();) would work without any issues. 我有几次遇到for-each循环会引起问题(包括异常和崩溃)的情况,而for(it=list.iterator;it.hasNext();)可以正常工作。 This includes modifying the collection (which I know shouldn't happen on for-each, but don't know why) as well as other cases where I clone stuff. 这包括修改集合(我知道不应在for-each上发生,但不知道为什么),以及其他克隆东西的情况。 Cant recall any specific example atm I just got thinking about it. 不能回忆起我刚想到的任何特定示例atm。

Isn't the for-each just a shortcut for the second loop type I pointed? for-each不仅仅是我指出的第二种循环类型的捷径吗? Could someone explain exactly whats the difference there? 有人可以解释一下到底有什么区别吗?

The problem is when in foreach loop you remove an element. 问题是在foreach循环中remove元素时。 When using an iterator you have a remove method. 使用迭代器时,您可以使用remove方法。 When using foreach you don't have a direct access to the underlying iterator and you can't call its remove method. 使用foreach您没有直接访问基础迭代器的权限,因此无法调用其remove方法。

Otherwise it is the same. 否则它是相同的。 Foreach doesn't cause more problems or crashes. Foreach不会导致更多问题或崩溃。 You just can't remove an element. 您只是无法删除元素。

for-each is just a syntactic sugar introduced in java 1.5. for-each只是Java 1.5中引入的语法糖。 It uses iterator obtained from Iterable behind the scene. 它使用在幕后从Iterable获得的迭代器。

The only one reasonable difference you mentioned is collection modification during iteration. 您提到的唯一一个合理的区别是迭代期间的集合修改。 Yes, it is impossible. 是的,这是不可能的。 Collections cannot be modified during iteration using Iterator . 在迭代期间,不能使用Iterator修改集合。 The attempt causes ConcurrentModificationException . 尝试导致ConcurrentModificationException This is relevant for both cases (explicit and implicit usage of iterator). 这与两种情况(显式和隐式使用迭代器)有关。

The only one exception is using Iterator.remove() (when it is supported). 唯一的例外是使用Iterator.remove() (受支持)。 In this case iterator does not throw the exception. 在这种情况下,迭代器不会引发异常。

The reason is clear. 原因很明显。 Iterator cannot iterate collection that is being changed during iteration unless it knows about the change and can re-arrange itself. 迭代器无法迭代在迭代过程中更改的集合,除非它知道更改并可以重新安排自身。 This is what happens when you are using Iterator.remove() . 这是在使用Iterator.remove()时发生的情况。

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

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