53
The usual form the of for each loop is this:
for(Foo bar: bars){
bar.doThings();
}
But if I want to retain bar until after the loop, I can not use the for each loop:
Foo bar = null;
// - Syntax error on token "bar", Identifier expected after this token
for(bar: bars){
if(bar.condition())
break;
}
bar.doThings();
The for loop gets the syntax error mentioned above.
Why is this? I'm not interested in workarounds, but just curious to the considerations behind this limitation.
In contrast, with an ordinary for loop, the variable can be declared outside or not at all...
int i = 1;
for(;i<max;i++){
for(;;){
// Do things
}
}