tags:

views:

104

answers:

4

I just came across the following code:

for(Iterator<String> iterator = stuff.iterator(); iterator.hasNext();) {
   ...
}

This strikes me as a sort of misuse of a for... Wouldn't this code be better as:

Iterator<String> iterator = stuff.iterator();
while(iterator.hasNext()) {
   ...
}

?

Any specific reasons anyone can think of to use the for? Which is the better approach?

+6  A: 

What is stuff? Can you apply enhanced for loop for it?

for (String str : stuff) {
   doSmth (str);
}

The only reason to use iterators explicitly is to remove certain elements while looping with iterator.remove().

Roman
I may be able to use a foreach in this situation... but what if it's not a native Java collection and is user-defined, so for-each can't be used but it has its own iterator?
froadie
just implement Iterable<T> for enable the use of for-each for your own objects
dfa
If it's an old (i.e. written with java 1.4 or earlier) 3rd-party library then I'd prefer while loop. It's more clean and makes code more readable.
Roman
+7  A: 

I'd prefer

for (String string : stuff) {
    ...
}

Much cleaner, and there is rarely an actual use for the Iterator.

The enhanced for loop can be applied to anything which implements Iterable, which only requires the iterator() method.

If that is not possible, I prefer the first version because it limits the scope of the iterator without requiring an extra set of brackets (you could wrap the while version inside {} to get the same effect, but with an additional level of indentation).

Michael Myers
A: 

Why don't you use a foreach loop? from 1.5..

for (Element el : collection) {
  // do whatever
}
Jack
+3  A: 

The for loop is better because the scope of the Iterator is limited to inside the loop.

Steve Kuo