Panasonic Youth

preferred Iterator usage - use "for", not "while"

Note: this tip not quite as applicable with Java 5.

One of my pet peeves is coming up this loop construct for iteration - don’t use this:

[java] Iterator iter = widgets.iterator(); while(iter.hasNext()) { foo(widgets.next()); }[/java]

Instead, use the “for loop idiom”. It minimizes the scope of the iterator and is a safer, shorter, and is clearer:

[java]for(Iterator iter = widgets.iterator(); iter.hasNext();) { foo(widgets.next()); }[/java]

Good ole’ Effective Java has a nice example of the kind of copy-and-paste bugs that can happen with the first idiom:

[java]Iterator i = c.iterator(); while(i.hasNext()) { foo(i.next()); } // other code Iterator i2 = c2.iterator(); while(i.hasNext()) { foo(i2.hasNext()); }[/java]

Do you see the bug? Its easy to see here, of course, but could be tough to find in practice as it runs fine but just functions incorrectly. It would be a compile time error if you went with the for construct. Its always best to keep your variable scope as small as possible, and the for loop also makes refactoring cleaner if you want to extract the loop block out.