0

I have the following piece of Java code

ImmutableList<Element> elements = ...;

for (Element e : elements) {
    e.doSomething();
}

where ImmutableList is part of the Guava library. NetBeans suggest me to convert the code using the `Convert to for (Iterator...) {}' suggestion which results in the following transformation

ImmutableList<Element> elements = ...;

for (Iterator<Element> it = elements.iterator(); it.hasNext();) {
    Element e = it.next();
    e.doSomething;
}

I fail to see a reason for this transformation. I'm using Java 1.7 and NetBeans 7.4. Can somebody enlighten me?

ooxi
  • 3,159
  • 2
  • 28
  • 41
  • possible duplicate of [Which is more efficient, a for-each loop, or an iterator?](http://stackoverflow.com/questions/2113216/which-is-more-efficient-a-for-each-loop-or-an-iterator) – Natan Streppel Jun 17 '14 at 12:17
  • I'm not claiming that yours is an exact duplicate of the question, but the answer to the proclaimed dup may be what you're looking for – Natan Streppel Jun 17 '14 at 12:19
  • @Streppel I read through the question you marked as duplicated (and the questions linked in there, too) but I still don't get why the more verbose and less declarative notation should be preferred. Especially since the answers to the questions indicate that both forms are functionally equivalent. – ooxi Jun 17 '14 at 12:34

1 Answers1

5

Conversions like this are sometimes worth doing as a first step in something else, and that's why your IDE gives you an easy way to do it correctly.

If you're going to leave the code exactly in the form given, there's no reason for the conversion. It's equivalent code. I would personally prefer to leave it in the more concise and expressive for-each form.

If you need to change your loop so it does something more complex, like removing from the list as you traverse it, the proper way to do that is with an iterator, and it can be easily added in the converted code.

Don Roby
  • 40,677
  • 6
  • 91
  • 113
  • But the suggestion is in the form of a warning like unchecked conversion of types. Maybe it's just an IDE bug and I should go to the NetBeans mailing list. – ooxi Jun 17 '14 at 12:36
  • It should be a warning in my opinion. Inquiring with Netbeans on that choice might be a good idea. – Don Roby Jun 17 '14 at 12:45
  • Yeah, there's no reason whatsoever to make that change... the for-each loop is more concise, more readable and does the exact same thing. IntelliJ IDEA, for example, would prompt you to make the exact _opposite_ change if you wrote the second form yourself. – ColinD Jun 17 '14 at 17:04
  • I typoed there. I meant it *shouldn't* be a warning. It's good to have it as an option. – Don Roby Jun 17 '14 at 17:33