Java:从匿名内部类访问局部变量? (PriorityQueue中) [英] Java: Access local variables from anon inner class? (PriorityQueue)

查看:259
本文介绍了Java:从匿名内部类访问局部变量? (PriorityQueue中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 PriorityQueue 在图上进行拓扑排序。为简洁起见,我想为比较器使用匿名内部类。然而,我需要访问图 g 来确定我正在查看的节点的入度。这可能吗?

I want to use a PriorityQueue to do a topological sort on a graph. For brevity, I'd like to use an anonymous inner class for the comparator. However, I need access to the graph g in order to determine the in degree of the nodes I'm looking at. Is this possible?

    /**
 * 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;
}

正确的代码 $ b

CORRECTED CODE

/**
 * 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;
}


推荐答案



Yes, make it final:

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

请参阅关于最终关键字的最终词:

涉及最终
变量的第二种情况实际上是由
语言语义规定的。在这种情况下,Java编译器
不会让你使用
变量,除非它被声明为final。
这种情况​​出现在闭包中,
也被称为匿名本地类。
本地类只能引用本地
变量和
声明为final的参数。

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
    }
  };
} 

如果我们释放一些光线,
如何实施本地类。
一个匿名的本地类可以使用本地的
变量,因为编译器
自动给这个类一个
的私有实例字段来保存这个类使用的每个局部变量的副本

编译器还向每个构造函数添加隐藏的
参数,以
初始化这些自动创建的
私有字段。因此,本地类
实际上不会访问本地
变量,而只是它自己的私人
副本。这个
可以正确工作的唯一方法是如果本地
变量被声明为final,那么
保证不会改变。
有了这个保证,
本地类可以确保其
变量
的内部副本准确地反映实际的本地
变量。

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:从匿名内部类访问局部变量? (PriorityQueue中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆