【问题标题】:Why class Node in LinkedList defined as static but not normal class [duplicate]为什么LinkedList中的类节点定义为静态而不是普通类[重复]
【发布时间】:2017-05-17 05:50:07
【问题描述】:

包java.util.LinkedList中,Class Node定义为一个静态类,有必要吗?目标是什么?

我们可以从这个page找到源代码。

【问题讨论】:

  • 它是静态的,因为一个 List<E> 中的一个 Node<E> 可以与来自其他每个 List<E> 的节点的类型相同。该类型不需要绑定到单个 List<E> 实例。
  • @PatrickParker 谢谢,很有帮助。

标签: java data-structures linked-list


【解决方案1】:

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

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

以这个类为例:

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

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

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

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

【讨论】:

  • 感谢这个例子,真的很容易理解。 Node 类型不需要绑定到单个 List 实例。
猜你喜欢
  • 2013-05-06
  • 1970-01-01
  • 1970-01-01
  • 2011-02-27
  • 2015-09-19
  • 2011-02-25
  • 1970-01-01
  • 2015-07-21
  • 1970-01-01
相关资源
最近更新 更多