相关疑难解决方法(0)

为什么在java中的for-each循环中需要声明变量

每个循环的通常形式是:

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 syntax foreach

52
推荐指数
1
解决办法
5632
查看次数

Java for循环语法:"for(T obj:objects)"

我遇到了一些我以前没见过的Java语法.我想知道是否有人能告诉我这里发生了什么.

for (ObjectType objectName : collectionName.getObjects())
Run Code Online (Sandbox Code Playgroud)

java syntax foreach for-loop

49
推荐指数
2
解决办法
15万
查看次数

标签 统计

foreach ×2

java ×2

syntax ×2

for-loop ×1