【问题标题】:nosuchElementException issue using iterator使用迭代器的 nosuchElementException 问题
【发布时间】:2014-12-15 16:35:38
【问题描述】:

当我的程序运行到集合的 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)

我编写了自己的迭代器,并使用了一个头节点和一个尾节点(它们的 Key 设置为 null)来轻松找到列表的开头和结尾。这个类在 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);
        }
    }
}

【问题讨论】:

    标签: java iterator nosuchelementexception


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      构造函数会是这样的

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-14
        • 1970-01-01
        • 2023-03-31
        • 2012-07-18
        • 1970-01-01
        • 2011-08-06
        • 2021-08-14
        相关资源
        最近更新 更多