Reputation: 143
Hi I'm very new to Java and trying to create a Deque
class by implementing a doubly linked-list format. When I run the code(DequeApp), I get a NullPointerException
refer back to my Iterator.next(Deque.java:44).
Error messages: **Exception in thread "main" java.lang.NullPointerException
at dlist.Deque$DoubleListIterator.next(Deque.java:44)
public E next() {
if (!hasNext()) {throw new NoSuchElementException();}
else{
E temp = current.item;
current = current.next;
return temp;}
}
Upvotes: 3
Views: 789
Reputation: 342
Another option to using index variable is
Maybe you could try "current.next != null" within hasNext.
But if it is already working with index no issues then.
Upvotes: 0
Reputation: 17955
You forgot to increment your index
counter in the DoubleListIterator
. You write:
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
} else {
E temp = current.item;
current = current.next;
return temp;
}
}
And you should have written:
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
} else {
index ++; // <---- without this, hasNext() always returns true
E temp = current.item;
current = current.next;
return temp;
}
}
Note also that I have changed the indenting format to that of Oracle's guidelines.
A second error is that you initialize your Iterator as follows:
private Node current=head.next;
However, this makes it impossible to retrieve head
(as you are already pointing to its next
node). And it makes you index counter off-by-one. Corrected code:
private Node current=head;
Upvotes: 2
Reputation: 2119
I have made two changes.
Start current from head, not head.next.
private class DoubleListIterator implements Iterator<E> {
// instance variable
private Node current = head;
private int index = 0;
public boolean hasNext() {
return index < N;
}
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
} else {
index++;
E temp = current.item;
current = current.next;
return temp;
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}
Upvotes: 3