Does Converting between loops always works like this? or there is some situation that it does not? and what is the fastest way to check while I\'m solving a question like th
The other members have covered the execution semantics. But I wanted to add the variable scoping semantics.
In Java, you can do this:
for (Iterator i = localList.iterator(); i.hasNext(); ) {
String element = i.next();
if (...) {
i.remove();
}
}
for (Iterator i = importList.iterator(); i.hasNext(); ) {
String element = i.next();
if (...) {
i.remove();
}
}
Where the variable 'i' is used twice.
In order to translate that to while loops with correct scoping, you need to use additional code blocks:
{
Iterator i = localList.iterator();
while (i.hasNext()) {
String element = i.next();
if (...) {
i.remove();
}
}
}
{
Iterator i = importList.iterator();
while (i.hasNext()) {
String element = i.next();
if (...) {
i.remove();
}
}
}
Note how the additional { ... } allows you to use the same variable names.
While not as important in Java, in languages like C++, the scoping has important ramifications beyond just being able to use the same variable names. Object destruction, IIA (instantiation is acquisition) etc are affected by the additional block.