for-each和for循环 [英] for-each and for loops

查看:82
本文介绍了for-each和for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几次遇到for-each循环会引起问题(包括异常和崩溃)的情况,而for(it=list.iterator;it.hasNext();)会毫无问题地工作.这包括修改集合(我知道不应该在for-each上发生,但不知道为什么),以及其他克隆东西的情况.不能回忆起我刚刚想到的任何特定示例atm.

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. 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. Cant recall any specific example atm I just got thinking about it.

for-each不仅仅是我指出的第二种循环类型的捷径吗?有人可以解释一下到底有什么区别吗?

Isn't the for-each just a shortcut for the second loop type I pointed? Could someone explain exactly whats the difference there?

推荐答案

for-each只是Java 1.5中引入的语法糖.它使用从Iterable幕后获得的迭代器.

for-each is just a syntactic sugar introduced in java 1.5. It uses iterator obtained from Iterable behind the scene.

您提到的唯一一个合理的区别是迭代期间的集合修改.是的,这是不可能的.不能在迭代期间使用Iterator修改集合.尝试导致ConcurrentModificationException.这与两种情况(显式和隐式使用迭代器)有关.

The only one reasonable difference you mentioned is collection modification during iteration. Yes, it is impossible. Collections cannot be modified during iteration using Iterator. The attempt causes ConcurrentModificationException. This is relevant for both cases (explicit and implicit usage of iterator).

唯一的例外是使用Iterator.remove()(受支持).在这种情况下,迭代器不会引发异常.

The only one exception is using Iterator.remove() (when it is supported). In this case iterator does not throw the exception.

原因很明显.迭代器无法迭代在迭代过程中更改的集合,除非它知道更改并可以重新安排自身.这是在使用Iterator.remove()时发生的情况.

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

这篇关于for-each和for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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