0

I know there are a lot of similar questions here on SO. But it seems this wasn't discussed before.

In general I want to know, why an Iterator should be used over a For-Each loop, if no element will be removed? So, basically just iterating over a Collection, and the only used modifier is add.

I'm aware that Iterator is the only save option if an element is removed from a Collection. Performance is no argument, because the For-Each will be transformed into an Iterator by the compiler. The Iterator is more verbose, so +1 to For-Each.

Is there any reliable point to use an Iterator over For-Each in the described scenario?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Steve Benett
  • 12,843
  • 7
  • 59
  • 79
  • 2
    I can't think of any compelling reason to, since they are essentially the same thing. I just think the for each looks nicer and is easier to read. – user489041 Mar 18 '15 at 16:42
  • I assume by foreach, you mean `for(Object o : yourCollection)`? In this case, you must be careful of a `ConcurrentModificationException` – TayTay Mar 18 '15 at 16:44
  • @Tgsmith61591 *"if no element will be removed"* – m0skit0 Mar 18 '15 at 16:45
  • 3
    You can get a `ConcurrentModificationException` if you're adding to the underlying collection, too. – yshavit Mar 18 '15 at 16:45
  • That's what I get for scanning the question. Here is another answer on this topic: http://stackoverflow.com/questions/256859/is-there-a-performance-difference-between-a-for-loop-and-a-for-each-loop – TayTay Mar 18 '15 at 16:46
  • I don't think this is an opinion based question. This is just a comparison between to ways for the same thing. If they would be exactly equal one would be redundant. – Steve Benett Mar 18 '15 at 16:47
  • 1
    @yshavit, yes, but *neither* approach being considered helps avoid a `ConcurrentModificationException` when adding elements to the underlying collection. – John Bollinger Mar 18 '15 at 16:53

1 Answers1

1

You need to use an Iterator loop instead of a foreach loop if

  • you need to be able to remove items during processing, OR
  • you need to process the last item differently than the others.

Also, an Iterator may be more natural if you want to be able to skip an element based on characteristics of its previous element.

Additionally, for Lists, a ListIterator loop may sometimes be more convenient than a foreach loop, as it can provide the indexes of the previous and next elements, and (even apart from the indexes) allows you to recognize the first element of the iteration. Furthermore, you need a ListIterator if

  • you have to replace elements in the underlying List, OR
  • you ever need to back up.
John Bollinger
  • 160,171
  • 8
  • 81
  • 157