繁体   English   中英

Java迭代器变量范围

[英]Java iterator variable scope

这是我刚编写的代码的一部分。 基本上, Document类实现了Iterable接口。 迭代器将像链接列表一样遍历节点。 remove方法中,我使用了Document类范围内的nodeMap引用。 但是, this引用应引用Iterator本身,因此它怎么能找到该对象? 还是IteratorDocument的子类?

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM