1

私のプログラムがコレクションの 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)

私は独自の Iterator を作成し、ヘッド ノードとテール ノード (キーを null に設定) を使用して、リストの最初と最後を簡単に見つけました。このクラスは、パッケージ positionalList の 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);  
    }
}

パッケージ「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);
        }
    }
}
4

2 に答える 2

4

問題はコンストラクタにあります:

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

同じ名前のローカル変数を作成して、変数をシャドーイングしています。これにより、インスタンス変数が留まるようにp「強制」されます。初めて呼び出す場合、 のチェックが true になり、.pnullnext()nullNoSuchElementException

タイプを削除するか、追加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();
}
于 2014-12-15T16:46:50.767 に答える
1

コンストラクタはこのようになります

public IteratorList(NodePositionList<K> n){
            this.npl = n;
            this.p = (npl.isEmpty()) ? null : npl.first();
    }
于 2014-12-15T16:45:41.963 に答える