每个循环的通常形式是:
for(Foo bar: bars){
bar.doThings();
}
Run Code Online (Sandbox Code Playgroud)
但是如果我想在循环之后保留bar,我就不能使用for循环:
Foo bar = null;
// - Syntax error on token "bar", Identifier expected after this token
for(bar: bars){
if(bar.condition())
break;
}
bar.doThings();
Run Code Online (Sandbox Code Playgroud)
for循环得到上面提到的语法错误.
为什么是这样? 我对解决方法不感兴趣,但只是对此限制背后的考虑因素感到好奇.
相反,对于普通的for循环,变量可以在外部声明或根本不声明...
int i = 1;
for(;i<max;i++){
for(;;){
// Do things
}
}
Run Code Online (Sandbox Code Playgroud) 我遇到了一些我以前没见过的Java语法.我想知道是否有人能告诉我这里发生了什么.
for (ObjectType objectName : collectionName.getObjects())
Run Code Online (Sandbox Code Playgroud)