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.
Isn’t the for-each just a shortcut for the second loop type I pointed? Could someone explain exactly whats the difference there?
for-eachis just a syntactic sugar introduced in java 1.5. It uses iterator obtained fromIterablebehind the scene.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 causesConcurrentModificationException. This is relevant for both cases (explicit and implicit usage of iterator).The only one exception is using
Iterator.remove()(when it is supported). 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().