for-each and for loops-Collection of common programming errors
for-each
is just a syntactic sugar introduced in java 1.5. It uses iterator obtained from Iterable
behind 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 causes 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). 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()
.