Giannis
Giannis

Reputation: 5526

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. 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?

Upvotes: 0

Views: 417

Answers (2)

AlexR
AlexR

Reputation: 115328

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

Upvotes: 3

Petar Minchev
Petar Minchev

Reputation: 47373

The problem is when in foreach loop you remove an element. When using an iterator you have a remove method. When using foreach you don't have a direct access to the underlying iterator and you can't call its remove method.

Otherwise it is the same. Foreach doesn't cause more problems or crashes. You just can't remove an element.

Upvotes: 5

Related Questions