1

これは、私が今書いたコードの一部です。基本的に、クラスはインターフェイスをDocument実装しIterableます。イテレータは、リンクされたリストのようにノードを反復処理します。removeメソッドでは、クラス スコープにある の参照を使用しましnodeMapDocument。ただし、this参照はIteratorそれ自体を参照する必要があるため、どのようにしてそのオブジェクトを見つけることができるのでしょうか? それともIteratorの子クラスDocumentですか?

私はこれまでこの質問について考えたことがありませんでした。突然、自分を混乱させました。

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

1 に答える 1

1

反復子は、クラスの匿名内部クラスのインスタンスですDocument。内部クラスには次の 2 種類があります。

  • 静的内部クラスは外部クラスのインスタンスに関連付けられていません。それらは、独自のメンバーと外部クラスの静的メンバーにのみアクセスできます。
  • 非静的内部クラスは、それらが作成されたコンテキスト内の外部クラスのインスタンスへの参照を所有しているため、外部クラスの非静的メンバーに直接アクセスできます。これは、コード内の反復子がインスタンスである種類のクラスです。
于 2013-03-10T18:48:11.183 に答える