gpt4 book ai didi

Java:从匿名内部类访问局部变量? (优先队列)

转载 作者:行者123 更新时间:2023-12-02 09:05:50 25 4
gpt4 key购买 nike

我想使用 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;
}

更正代码

/**
* topological sort
* @param g must be a dag
*/
public static Queue<String> topoSort(final DirectedGraph<String, DefaultEdge> g) {
Queue<String> result = new PriorityQueue<String>(g.vertexSet().size(),
new Comparator<String>() {
@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;
}

最佳答案

是的,最终确定:

public static Queue<String> topoSort(final DirectedGraph<String, DefaultEdge> g) {

参见The Final Word On the final Keyword :

Anonymous Local Classes

The second situation involving final variables is actually mandated by language semantics. In that situation, the Java compiler won't let you use a variable unless it is declared final. This situation arises with closures, also known as anonymous local classes. Local classes can only reference local variables and parameters that are declared final.

public void doSomething(int i, int j)
{
final int n = i + j; // must be declared final

Comparator comp = new Comparator()
{
public int compare(Object left, Object right)
{
return n; // return copy of a local variable
}
};
}

The reason for this restriction becomes apparent if we shed some light on how local classes are implemented. An anonymous local class can use local variables because the compiler automatically gives the class a private instance field to hold a copy of each local variable the class uses. The compiler also adds hidden parameters to each constructor to initialize these automatically created private fields. Thus, a local class does not actually access local variables, but merely its own private copies of them. The only way this can work correctly is if the local variables are declared final, so that they are guaranteed not to change. With this guarantee in place, the local class is assured that its internal copies of the variables accurately reflect the actual local variables.

关于Java:从匿名内部类访问局部变量? (优先队列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1746219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com