编辑:我需要更改几个变量的值,因为它们通过计时器运行几次.我需要通过计时器每次迭代不断更新值.我无法将值设置为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 …
为什么我需要声明local variable的final,如果我的Inner class方法中定义需要使用它?
示例:
class MyOuter2 {
private String x = "Outer2";
void doStuff() {
final String y = "Hello World";
final class MyInner {
String z = y;
public void seeOuter() {
System.out.println("Outer x is "+x);
System.out.println("Local variable is "+y);
MyInner mi = new MyInner();
mi.seeOuter();
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
为什么String y需要是最终常量?它是如何影响的?
我想使用a PriorityQueue在图形上进行拓扑排序.为简洁起见,我想为比较器使用匿名内部类.但是,我需要访问图表g以确定我正在查看的节点的程度.这可能吗?
/**
* topological sort
* @param g must be a dag
*/
public static Queue<String> topoSort(DirectedGraph<String, DefaultEdge> g) {
Queue<String> result = new PriorityQueue<String>(g.vertexSet().size(),
new Comparator<String>() {
DirectedGraph<String, DefaultEdge> g;
@Override
public int compare(String arg0, String arg1) {
if (g.inDegreeOf(arg0) < g.inDegreeOf(arg1)) {
return -1;
}
if (g.inDegreeOf(arg0) > g.inDegreeOf(arg1)) {
return 1;
}
return 0;
}
});
result.addAll(g.vertexSet());
return result;
}
Run Code Online (Sandbox Code Playgroud)
正确的代码
/**
* topological sort
* @param g must be a dag
*/ …Run Code Online (Sandbox Code Playgroud)