Java:将参数化类型的局部类用于局部类内引用的局部变量



我在Java中的单个方法中实现了某种算法。该算法需要不会在其他任何地方使用的数据结构,因此对我来说使用本地类似乎是合适的。算法的最后一步需要遍历之前在方法中创建的所有对象,因此我想我会让本地类的构造函数将新创建的对象添加到列表中。在 Java 中,局部类可以访问声明final的局部变量。所以我尝试了这样的事情:

public void doThing() {
    class Foo {
        public Foo() {
            fooList.add(this);  // FAILS: "cannot find symbol: variable fooList"
        }
    }
    final ArrayList<Foo> fooList = new ArrayList<Foo>();
    // algorithm goes here, instantiating some Foo objects:
    Foo foo = new Foo();
    // etc.
    // now iterate through all the Foo objects that were created
    for (Foo f : fooList)
        System.out.println(f);
}

这失败了,因为显然我必须先声明fooList然后才能在本地类中引用它。 好吧,好吧,我想,我将在方法的开头声明fooList

public void doThing() {
    final ArrayList<Foo> fooList;  // FAILS: "cannot find symbol: class Foo"
    class Foo {
        public Foo() {
            fooList.add(this);
        }
    }
    fooList = new ArrayList<Foo>();
    Foo foo = new Foo();
    for (Foo f : fooList)
        System.out.println(f);
}

但这也会失败,因为显然我需要在引用之前定义Foo类。那么如何打破这种循环依赖呢?

那么如何打破这种循环依赖呢?

我强烈建议将本地类分解为私有静态嵌套类。我不能说我曾经见过在方法中声明的命名类的愉快使用。虽然我通常对"它只用于一种方法"部分表示赞赏,但当你声明类时,该方法已经达到了中等长度。

当然,您始终可以为声明使用原始类型,稍后再强制转换......这可能会起作用,但显然会很可怕。

另一种选择:

class Foo {
    public Foo(ArrayList<Foo> fooList) {
        fooList.add(this);
    }
    public Foo() {
    }
}
public void doThing() {
    final ArrayList<Foo> fooList = new ArrayList<Foo>();
    Foo foo = new Foo(fooList);
    // or simply fooList.add(new Foo());

    for (Foo f : fooList)
        System.out.println(f);
}

我认为以这种方式添加引用以列出是一个坏主意。在这种情况下,您可以简单地编写new Foo(fooList);引用将在列表中,但您不会在方法中保存引用。这取决于您要做什么,因此请使用最舒适的变体

最新更新