2014-12-15 4 views
1

У меня есть эта printStackTrace когда моя программа опускает в течение коллекцииNoSuchElementException вопрос с использованием итератора

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) 

я написал свой собственный итератор, и я использовал головной узел и хвостовой узел (с их набором ключей для 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); 
     } 
    } 
} 

ответ

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

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

public IteratorList(NodePositionList<K> n){ 
      this.npl = n; 
      this.p = (npl.isEmpty()) ? null : npl.first(); 
    } 
Смежные вопросы