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?
What is
stuff? Can you apply enhanced for loop for it?The only reason to use iterators explicitly is to remove certain elements while looping with
iterator.remove().