Java Iterator Doubly Linked List
Hi I am very new to Java and am trying to create a class Deque
implementing a double join format. When I run the code (DequeApp) I get NullPointerException
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;}
}
source to share
I made two changes.
- As tucuxi already said, the index of the increment.
-
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(); } }
source to share
You forgot to increase your counter index
in 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;
}
}
Also note that I have changed the indentation format to follow Oracle guidelines.
The second error is when you initialize your Iterator like this:
private Node current=head.next;
However, this does not allow getting head
(since you are already pointing to its next
node). And it makes you an index counter one by one. Corrected code:
private Node current=head;
source to share