froadie
froadie

Reputation: 83183

Is it better to use a "partial" for loop for this code or a while loop?

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?

Upvotes: 0

Views: 263

Answers (4)

Steve Kuo
Steve Kuo

Reputation: 63134

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

Upvotes: 4

Roman
Roman

Reputation: 66216

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

Upvotes: 6

Jack
Jack

Reputation: 133639

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

for (Element el : collection) {
  // do whatever
}

Upvotes: 0

Michael Myers
Michael Myers

Reputation: 192035

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

Upvotes: 7

Related Questions