Проблема nosuchElementException с использованием итератора

У меня есть этот 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);  
    }
}

Я назвал его этим кодом, принадлежащим пакету "алгоритмо".

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

person johnny_kb    schedule 15.12.2014    source источник


Ответы (2)


Проблема в вашем конструкторе:

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

Вы затеняете переменную p, создавая локальную переменную с тем же именем. Это «заставляет» переменную экземпляра p оставаться null. Если вы вызываете next() в первый раз, проверка для null будет истинной, что запускает ваш NoSuchElementException.

Либо удалите тип, либо добавьте к нему this:

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();
}
person Tom    schedule 15.12.2014

Конструктор будет таким

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