我在Java 8中玩lambdas,我遇到了警告local variables referenced from a lambda expression must be final or effectively final.我知道当我在匿名类中使用变量时,它们必须在外部类中是最终的,但仍然 - 最终和有效最终之间有什么区别?
编辑:我需要更改几个变量的值,因为它们通过计时器运行几次.我需要通过计时器每次迭代不断更新值.我无法将值设置为final,因为这会阻止我更新值,但是我收到了我在下面的初始问题中描述的错误:
我以前写过以下内容:
我收到错误"不能引用在不同方法中定义的内部类中的非final变量".
这种情况发生在双重调用价格和价格调用priceObject上.你知道我为什么会遇到这个问题.我不明白为什么我需要最后的声明.此外,如果你能看到我想要做的是什么,我该怎么做才能解决这个问题.
public static void main(String args[]) {
int period = 2000;
int delay = 2000;
double lastPrice = 0;
Price priceObject = new Price();
double price = 0;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
price = priceObject.getNextPrice(lastPrice);
System.out.println();
lastPrice = price;
}
}, delay, period);
}
Run Code Online (Sandbox Code Playgroud) 在方法内部定义的内部类不能访问方法的局部变量,除非标记了这些局部变量.我已经final查看了堆栈溢出和java代码牧场中的其他帖子,但它们似乎都没有完全回答关于如何标记的问题变量final允许内部类访问方法中的局部变量.
class MyOuter {
private String x = "Outer";
void fly(final int speed) {
final int e = 1;
class FlyingEquation {
public void seeOuter()
{
System.out.println("Outer x is " + x);
}
public void display()
{
System.out.println(e);// line 1
System.out.println(speed);// line 2
}
}
FlyingEquation f=new FlyingEquation();
f.seeOuter();
f.display();
}
public static void main(String args[])
{
MyOuter mo=new MyOuter();
mo.fly(5);
}
}
Run Code Online (Sandbox Code Playgroud)
我发现的解释:
局部变量存储在堆栈中,一旦方法调用完成,就会弹出堆栈并且局部变量不可访问,而 最终局部变量存储在内存的数据部分中,JVM即使在方法调用结束后也可能允许访问它们.在哪里data …