使用迭代器的nosuchElementException问题

时间:2014-12-15 16:35:39

标签: java iterator nosuchelementexception

当我的程序遇到Collection

时,我有这个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)

我编写了自己的迭代器,并使用了头节点和尾节点(其Key设置为null)来轻松查找列表的开头和结尾。此类位于NodeList

包中的NodePositionList类中
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);  
    }
}

我使用此代码调用它,属于包&#34; algoritmo&#34;。

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

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

构造函数将是这样的

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