Java的lambda - for循环计数器不是有效的最终 [英] Java lambda - for loop counter is not effectively final

查看:1061
本文介绍了Java的lambda - for循环计数器不是有效的最终的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



编译器抱怨我没有实际的最终结果,所以在这种情况下,lambda是在for循环中的,我希望计数器是有效的。我必须使用i2。

  for(int i = 0; i< x.getBooks()。size();我++){
//编译器需要我有效地最终。
int i2 = i;
列表< Book> books = bookstore.stream()
.filter(c - > c.getAuthors().get(i2).equals(xxx))
.collect(Collectors.toList());





$ b

所以问题是为什么我不是有效的最终的范围内的for这是最简单的解决方法。

不是 final ,因为它在的每次迭代中被修改( i ++ 循环。





为什么我不能在for循环?


循环语法的是 $ b $(b




$ $ $ $ $ $ $ $ >

增量表达式在循环的每次迭代之后被调用。在你的情况下,increment是 i ++ ,所以在每次迭代之后修改 i 。 b $ b

您可以通过声明 i final来确认:

  for(final int i = 0; i< x.getBooks()。size(); i ++){
}

你会得到这个编译错误:

 最后的局部变量i不能被赋值。 
它必须是空的,不能使用复合赋值







是最简单的解决方法吗?

for loop:yes。



但是你可以使用循环通过 @dkatzel foreach

  int i = 0; 
for(Book book:x.getBooks()){
int i2 = i;
...
i ++;
}


Given this situation where a lambda is inside a for loop I would expect the counter i to be effectively final.

The compiler complains that i is not effectively final so I had to use i2.

for (int i = 0; i < x.getBooks().size(); i++){
   //The compiler needs i to be effectively final.
   int i2 = i;
   List<Book> books = bookstore.stream()
                    .filter(c -> c.getAuthors().get(i2).equals("xxx"))
                    .collect(Collectors.toList());
}

So the question is why i is not effectively final inside the scope of the for loop and is this the simplest workaround.

解决方案

TLDR: i is not final because it is modified (i++) at each iteration of the for loop.


why i is not effectively final inside the scope of the for loop ?

The for loop syntax is

for (initialization; termination; increment) {
    statement(s)
}

The increment expression is invoked after each iteration through the loop. In your case, increment is i++ so i is modified after each iteration.

You could confirm this by declaring i final:

for (final int i = 0; i < x.getBooks().size(); i++) {
}

you will get this compilation error:

The final local variable i cannot be assigned.
It must be blank and not using a compound  assignment


is this the simplest workaround ?

In the case of a for loop: yes.

But you could use a while loop as shown by @dkatzel or a foreach:

int i = 0;
for (Book book: x.getBooks()) {
    int i2 = i;
    ...  
    i++;
}

这篇关于Java的lambda - for循环计数器不是有效的最终的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆