迭代数据结构和嵌套类

时间:2014-04-25 01:37:11

标签: java loops linked-list

我有一些代码用于迭代器,但我无法理解它是如何工作的。特别让我感到困惑的是public Node<T> front;for声明。

Front是对静态嵌套类的引用,在for循环中我们有LinkedList.Node<String> ptr = list.front。该操作的左侧只是访问外部类,然后访问我们进行ptr引用的静态嵌套类。该操作的右侧使用外部类的对象来访问前引用,也就是静态嵌套类。

那么左右两侧是不是一样的东西?为什么代码设置一边等于另一边?我知道提供的代码不完整 - 我没有写。我只是想了解它。

public class LinkedList<T> {
    public static class Node<E> {
        public E data;
        public Node<E> next;
    }
    public Node<T> front;

    ...code omitted...
}


LinkedList<String> list = new LinkedList<String>();

...code omitted...

for (LinkedList.Node<String> ptr = list.front; ptr != null; ptr = ptr.next) {
    System.out.println(ptr.data);
}

1 个答案:

答案 0 :(得分:2)

开始,&#34;前面&#34;不是对静态嵌套类的引用。它是对&#34;实例&#34;的引用。那个阶级,这是一个重要的区别。将该类视为创建实例的模板。

所以在某些时候,有人会创建对象:

LinkedList<String> list = new LinkedList<String>();
list.front = new LinkedList.Node<String>();
list.front.data = "foo";

然后可能会将一个节点添加到列表中(这通常是您更改LinkedList的方式,因为追加是昂贵的)

// Create the new node
LinkedList.Node<String> newNode = new LinkedList.Node<String>();
newNode.data = "bar";
// Since we're prepending, the existing front becomes the next for this node.
newNode.next = list.front;
// This node becomes the front of the list
list.front = newNode;

对于for语句,将其视为while循环,对人们来说更容易阅读

LinkedList.Node<String> ptr = list.front;
while (ptr != null) {
  // do something
  ptr = ptr.next;
}

回答关于&#34;静态&#34;的问题类:

内部类就像任何其他类一样。它只是在外部类中命名空间。然而,有两种类型的内部类。静态味道:

  1. 可以在其上实例化
  2. 与外部类的任何特定实例无关
  3. 相反,非静态内部类:

    1. 必须通过包含类
    2. 的实例进行实例化
    3. 可以访问包含类的实例的所有字段和方法。
    4. 以此代码示例:

      public class Outer {
          private int value = 10;
      
          public static class StaticInner {
      
          }
      
          public class Inner {
              public void foo() {
                  System.out.println(value);
              }
          }
      
          public Inner createInner() {
              return new Inner();
          }
      
          public static void main(String[] args) {
              Outer outer = new Outer();
              StaticInner staticInner = new StaticInner();
              Inner inner = outer.new Inner();
              Inner inner2 = outer.createInner();
          }
      }
      

      实际上,main方法的最后两个调用正在做同样的事情。您需要一些不同的语法来从包含类外部创建实例。但是在两种情况下你都会注意到,你需要先创建一个Outer实例,而要获得一个StaticInner实例,你却没有。

      您还会注意到,在非静态字段中,您可以访问私有字段&#34; value&#34;它包含实例。

      你可能想看这里:

      http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

相关问题