开发者

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

开发者 https://www.devze.com 2022-12-24 09:24 出处:网络
I just came across the following code: 开发者_开发技巧for(Iterator<String> iterator = stuff.iterator(); iterator.hasNext();) {

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?


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


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


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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号