java:是否可以为Buttons数组设置lambda表达式是for循环?如果是这样的话? [英] java: Is it possible to set a lambda expression for an array of Buttons is a for loop? If so how?
问题描述
我希望能够做到这样的事情:
I want to be able to do something like this:
for(i = 0; i < 10; i++) {
//if any button in the array is pressed, disable it.
button[i].setOnAction( ae -> { button[i].setDisable(true) } );
}
但是,我收到错误说局部变量从lambda表达式引用必须是final或者有效的final
。我怎么还能像上面的代码那样做(如果可能的话)?如果无法完成,应该做些什么来获得类似的结果?
However, I get a error saying "local variables referenced from a lambda expression must be final or effectively final"
. How might I still do something like the code above (if it is even possible)? If it can't be done, what should be done instead to get a similar result?
推荐答案
如错误信息所示,从lambda表达式引用的局部变量必须是final或者有效的final(有效的final意味着编译器可以让它最终为你)。
As the error message says, local variables referenced from a lambda expression must be final or effectively final ("effectively final" meaning the compiler can make it final for you).
简单的解决方法:
for(i = 0; i < 10; i++) {
final int ii = i;
button[i].setOnAction( ae -> { button[ii].setDisable(true) } );
}
这篇关于java:是否可以为Buttons数组设置lambda表达式是for循环?如果是这样的话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!