2013-03-10 91 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的匿名內部類的實例。有兩種內部類:

  • 的靜態內部類沒有連接到外部類的一個實例,他們只能訪問自己的成員和外部類的靜態成員。
  • 非靜態內部類在創建它們的上下文中擁有對外部類實例的引用,因此它們可以直接訪問外部類的非靜態成員。這是你的代碼中的迭代器是一個實例的類。