问题描述
我有一个小问题.当我编写此for循环时,f.getAnswerScore().get(i)....中的变量i
用错误消息加下划线:-我在封闭范围内定义的局部变量必须是final或 有效地最终.这与流有关吗?也许不能在循环中使用流?
I have a little problem. When I write this for loop, the variable i
in f.getAnswerScore().get(i).... is underlined with error message : - Local variable i defined in an enclosing scope must be final or effectively final. Does this have something to do with streams? Maybe streams can't be used in loops?
for (int i = 0; i < 10; i++) {
correct = active.stream()
.filter(f -> f.getAnswerScore().get(i).getStatus().equals(AnswerStatus.ANSWERED_CORRECT))
.count();
}
推荐答案
就像匿名内部类一样,lambda表达式只能访问局部变量,如果它们是final
或有效最终"变量,则它们只能访问局部变量. (Java 8或更高版本;不是final
,但一旦分配就永远不会更改.)
Like anonymous inner classes, lambda expressions can only access local variables if they are final
or "effectively final" (Java 8 or higher; not final
but never changed once assigned).
任何在lambda主体中使用但未声明的局部变量必须在lambda主体之前进行明确赋值(第16节(确定赋值)),否则会发生编译时错误.
Any local variable used but not declared in a lambda body must be definitely assigned (§16 (Definite Assignment)) before the lambda body, or a compile-time error occurs.
关于变量使用的类似规则适用于内部类的主体(第8.1.3节).对有效最终变量的限制禁止访问动态变化的局部变量,因为局部变量的捕获可能会引入并发问题.与最终限制相比,它减轻了程序员的文书负担.
Similar rules on variable use apply in the body of an inner class (§8.1.3). The restriction to effectively final variables prohibits access to dynamically-changing local variables, whose capture would likely introduce concurrency problems. Compared to the final restriction, it reduces the clerical burden on programmers.
声明一个等于i
的final
变量并使用它.
Declare a final
variable equal to i
and use it.
for(int i = 0; i< 10; i++){
final int j = i;
correct = active
.stream()
.filter(f-> f.getAnswerScore().get(j).getStatus().equals(AnswerStatus.ANSWERED_CORRECT))
.count();
}
这篇关于Java8 Stream编译器消息-局部变量必须是final或有效的final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!