johnny_kb
johnny_kb

Reputation: 714

nosuchElementException issue using iterator

I have this printStackTrace when my program run into the for of a Collection

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)

I wrote my own Iterator, and i used a head node and a tail node (with their Key set to null) to find easily the beginning and the end of the list. This class is inside the NodePositionList class, in the package 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);  
    }
}

I called it with this code, that belongs to the package "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);
        }
    }
}

Upvotes: 1

Views: 440

Answers (2)

Tom
Tom

Reputation: 17577

The problem is in your constructor:

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

You're shadowing the variable p by creating a local variable with the same name. That "forces" the instance variable p to stay null. If you call next() for the first time, the check for null will be true, which triggers your NoSuchElementException.

Either remove the type or add this to it:

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

Or:

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

Upvotes: 4

Siva Kumar
Siva Kumar

Reputation: 2006

Constructor will be like this

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

Upvotes: 1

Related Questions