java中for循环中计数器_Javalambda–forfor循环计数器不是最
终的
TLDR:我不是最终的,因为它在for循环的每次迭代中被修改(i).variable used in lambda
why i is not effectively final inside the scope of the for loop ?
for循环语法是
for (initialization; termination; increment) {
statement(s)
}
每次迭代循环后都会调⽤increment表达式.在你的情况下,增量是i所以我在每次迭代后修改.
您可以通过声明我的最终结果来确认这⼀点:
for (final int i = 0; i < x.getBooks().size(); i++) {
}
你会得到这个编译错误:
The final local variable i cannot be assigned.
It must be blank and not using a compound assignment
is this the simplest workaround ?
在for循环的情况下:是的.
但你可以使⽤@dkatzel或foreach所⽰的while循环:
int i = 0;
for (Book book: x.getBooks()) {
int i2 = i;
...
i++;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。