Robert
Robert

Reputation: 143

Java Iterator Doubly Linked list

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

Answers (3)

acearch
acearch

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

tucuxi
tucuxi

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

Aakash
Aakash

Reputation: 2119

I have made two changes.

  1. As tucuxi already told, increment index.
  2. 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

Related Questions