Comment Re:What's wrong with a while loop? (Score 2, Informative) 114
The problem is that i is outside the scope of the loop. However, it is only needed within the loop. If you don't have any other loops in the vicinity, then you are okay, but consider this:
Iterator i = obj.iterator();
while (i.hasNext()) {
}
Iterator i = obj.iterator();
while (i.hasNext()) {
}
Whoops, this doesn't compile. There's a few ways out of this:
Iterator i = obj.iterator();
while (i.hasNext()) {
}
i = obj.iterator();
while (i.hasNext()) {
}
The problem with this is that if you delete the first loop, you have the remember to change the second loop. (This is why reusing variables to do different things is not a good idea.) Here's another approach:
Iterator i = obj.iterator();
while (i.hasNext()) {
}
Iterator i2 = obj.iterator();
while (i2.hasNext()) {
}
The problem with this is that you might forget to change all references from i to i2. Now consider the "standard" solution:
for(Iterator i = obj.iterator(); i.hasNext();) {
}
for(Iterator i = obj.iterator(); i.hasNext();) {
}
Here, each Iterator is in its own scope and you can easily refactor one loop without dealing with the other.