2013-03-10 83 views
1

下面是我刚刚写的代码的一部分。基本上Document类实现了Iterable接口。迭代器将像链表一样遍历节点。在remove方法中,我使用了nodeMap的参考,它在Document类范围内。然而this参考应该参考Iterator本身,所以它怎么能找到这个对象?或者是IteratorDocument的子类?Java迭代器变量范围

我以前没有想过这个问题。突然让我感到困惑。

public class Document implements Iterable<DocumentNode> { 
    Map<Integer, DocumentNode> nodeMap; 

    public Iterator<DocumentNode> iterator() { 
     return new Iterator<DocumentNode>() { 
      DocumentNode node = nodeMap.get(0); 

      @Override 
      public boolean hasNext() { 
       return node != null && node.next != null; 
      } 

      @Override 
      public DocumentNode next() { 
       if (node == null) { 
        throw new IndexOutOfBoundsException(); 
       } 
       return node.next; 
      } 

      @Override 
      public void remove() { 
       if (node == null) { 
        throw new IndexOutOfBoundsException(); 
       } 
       if (node.prev != null) { 
        node.prev.next = node.next; 
       } 
       if (node.next != null) { 
        node.next.prev = node.prev; 
       } 
       nodeMap.remove(node.documentID); 
      } 
     }; 
    } 
} 
+0

你的意思是:在'Iterator'匿名内部类中怎么可以访问'nodeMap'? – 2013-03-10 18:50:59

回答

1

该迭代器是类Document的匿名内部类的实例。有两种内部类:

  • 的静态内部类没有连接到外部类的一个实例,他们只能访问自己的成员和外部类的静态成员。
  • 非静态内部类在创建它们的上下文中拥有对外部类实例的引用,因此它们可以直接访问外部类的非静态成员。这是你的代码中的迭代器是一个实例的类。