[英] Difference between final and effectively final
我在玩Java 8中的lambdas时遇到了警告local variables referenced from a lambda expression must be final or effectively final
.我知道,当我在匿名类中使用变量时,它们在外部类中必须是最终的,但是——final和effectively final之间的区别是什么?
我在玩Java 8中的lambdas时遇到了警告local variables referenced from a lambda expression must be final or effectively final
.我知道,当我在匿名类中使用变量时,它们在外部类中必须是最终的,但是——final和effectively final之间的区别是什么?
... 从JavaSE8开始,局部类可以访问封闭块的局部变量和参数,这些变量和参数是final或实际上是final.A variable or parameter whose value is never changed after it is initialized is effectively final.
例如,假设变量numberLength
未声明为final,并在PhoneNumber
构造函数中添加标记的赋值语句:
public class OutterClass {
int numberLength; // <== not *final*
class PhoneNumber {
PhoneNumber(String phoneNumber) {
numberLength = 7; // <== assignment to numberLength
String currentNumber = phoneNumber.replaceAll(
regularExpression, "");
if (currentNumber.length() == numberLength)
formattedPhoneNumber = currentNumber;
else
formattedPhoneNumber = null;
}
...
}
...
}
由于这个赋值语句,变量numberLength实际上不再是最终的.As a result, the Java compiler generates an error message similar to "local variables referenced from an inner class must be final or effectively final",其中内部类PhoneNumbertry 访问numberLength变量:
http://codeinventions.blogspot.in/2014/07/difference-between-final-and.html
http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html
RandomGenerator (L32X64MixRandom) 的默认算法每次生成相同的数字
为什么最近调用 onAdDismissedFullScreenContent ?
如何在使用 Stream API 的函数更改字符串变量时跟踪它?
如何在 Java 中格式化两个 LocalDate 变量的范围?
如何在执行 Collectors.toMap() 之前删除会导致冲突的键
如何通过 SnowSQL 或 Java 函数将十六进制“F933F177”转换为十进制 -114.036361?
打印所有可以使用 `+` 或 `-` 运算符给出给定数字的组合
如何使用 Math.random() 在 Java 中模拟 60% 的概率