java - 使用迭代器的 nosuchElementException 问题

标签 java iterator nosuchelementexception

当我的程序运行到集合的 for 时,我有这个 printStackTrace

Exception in thread "main" java.util.NoSuchElementException: No next element
at positionalList.NodePositionList$IteratorList.next(NodePositionList.java:177)
at positionalList.NodePositionList$IteratorList.next(NodePositionList.java:1)
at positionalList.Ricerca.DFS(Ricerca.java:130)
at positionalList.Ricerca.main(Ricerca.java:291)

我编写了自己的迭代器,并使用头节点和尾节点(将它们的键设置为空)轻松找到列表的开头和结尾。这个类在 NodePositionList 类里面,在包 positionalList 中

private class IteratorList<T> implements Iterator<K> {
    protected NodePositionList<K> npl;
    protected Position<K> p;

    @SuppressWarnings("unused")
    public IteratorList(NodePositionList<K> n) {
            this.npl = n;
            Position<K> p = (npl.isEmpty()) ? null : npl.first();
    }

    @Override
    public boolean hasNext() {
        return  p != tail;
    }

    @Override
    public K next() throws NoSuchElementException {
        if (p == null) {
            throw new NoSuchElementException("No next element");
        }
        K toReturn = p.element();
        p = (p == npl.getTail()) ? null : npl.next(p);
        return toReturn;
    }

    @Override
    public void remove() {
        if (p == null) {
            throw new NoSuchElementException("No element to remove");
        }
        p = npl.remove(p);  
    }
}

我用这个代码调用它,它属于包“algoritmo”。

public static <T extends Comparable<T>> void DFS(TDAGraph<T> g) {
    for (Vertex<T> v: g.vertices()) {
        if (v.getColor() == VertexColor.WHITE) {
            DFS_visit(g,v);
        }
    }
}

最佳答案

问题出在你的构造函数中:

public IteratorList(NodePositionList<K> n){
    this.npl = n;
    Position<K> p = (npl.isEmpty()) ? null : npl.first();
}

你是 shadowing通过创建具有相同名称的局部变量,变量 p 。这“强制”实例变量 p 保持 null。如果您第一次调用 next(),对 null 的检查将为真,这将触发您的 NoSuchElementException

要么删除类型,要么向其添加 this:

public IteratorList(NodePositionList<K> n){
    this.npl = n;
    p = (npl.isEmpty()) ? null : npl.first();
}

或者:

public IteratorList(NodePositionList<K> n){
    this.npl = n;
    this.p = (npl.isEmpty()) ? null : npl.first();
}

关于java - 使用迭代器的 nosuchElementException 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27488715/

相关文章:

java - org.hibernate.StaleStateException : Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

rust - 如何使用可能失败的函数调用 Iterator .map()?

c++ - 迭代器 - 在 C++11 中没有匹配的删除函数

java - 我的 Java 代码中不断出现 NoSuchElement 异常。我的代码有什么问题吗?

java - 布局错误无法弄清楚

java - JMF 中的视频效果

java - 如何从控制台读取字符串? NoSuchElementException : No line found

java - 读取文件时出现无此类元素异常

java - 跨 jvms 的对象的对象 ID?

iterator - 为什么 Fuse 迭代器适配器没有按预期工作?