Мой итератор метод hasNext () возвращает false, когда не должен. Когда я создаю новый ток узла и сначала устанавливаю его равным узлу, он возвращает false. Но когда я использую Node первым вместо current (даже если current установлен на first), hasNext () и next () работают нормально.
public class StackNew implements Stack,Iterable{
private int elementCount;
private Node first;
private static class Node {
public Object data;
public Node next;
}
public Iterator asIterator() {
return new ListIterator(first);
}
private class ListIterator implements Iterator {
private Node current; //I had tried deleting this, and replaced all
currents with first, and worked fine
public ListIterator(Node first) {
current = first;
}
public boolean hasNext(){
return current != null;
}
public Object next() {
if (!hasNext()) throw new NoSuchElementException();
Object data = current.data;
current = current.next;
return data;
}
public Object peek() {
if (current == null) {
throw new NoSuchElementException();
}
return current.data;
}
}
генерирует исключение NoSuchElementException в next (), потому что hasNext () имеет значение null. Когда все должно быть хорошо, потому что first не нуль.