为什么LinkedList中的Node类定义为静态而不是普通类

Iva*_*van 4 java linked-list data-structures

在包java.util.LinkedList中,将类节点定义为一个静态类,是否有必要?目标是什么?

我们可以从此页面找到源代码。

Ger*_*cke 5

静态嵌套类的实例没有引用嵌套类的实例。与将它们放在单独的文件中基本上相同,但是如果与嵌套类的内聚性很高,则将它们作为嵌套类是一个不错的选择。

但是,非静态嵌套类需要创建嵌套类的实例,并且实例绑定到该实例并可以访问其字段。

以此类为例:

public class Main{

  private String aField = "test";

  public static void main(String... args) {

    StaticExample x1 = new StaticExample();
    System.out.println(x1.getField());


    //does not compile:
    // NonStaticExample x2 = new NonStaticExample();

    Main m1 = new Main();
    NonStaticExample x2 = m1.new NonStaticExample();
    System.out.println(x2.getField());

  }


  private static class StaticExample {

    String getField(){
        //does not compile
        return aField;
    }
  }

  private class NonStaticExample {
    String getField(){
        return aField;
    }
  }
Run Code Online (Sandbox Code Playgroud)

静态类StaticExample可以直接实例化,但不能访问嵌套类的实例字段Main。非静态类NonStaticExample需要实例Main化才能实例化,并且可以访问instance字段aField

回到您的LinkedList示例,它基本上是一种设计选择。

的实例Node不需要访问LinkedList的字段,但是将它们放在单独的文件中也是没有意义的,因为Node是实现的实现细节,LinkedList并且在该类之外没有任何用处。因此,使其成为静态嵌套类是最明智的设计选择。