-2

Hi I'm very new to Java and have this problem with building a nested Iterator class for a Doubly Linked List. I'm getting this error on E next method when running the test program. The goal of the next method in the Iterator is to return the next item in the Doubly Linked List.

Can anyone advice a fix on my code? Any help is greatly appreciated!

Error message:

Exception in thread "main" java.lang.NullPointerException at dlinkedlist.Deque$DoubleListIterator.next(Deque.java:51)

    public E next() {
        if (!hasNext()) throw new NoSuchElementException();
        last = current;
        E value = current.item;
        current = current.next; 
        index++;
        return value;
    }
    public void remove() { throw new UnsupportedOperationException(); }
  }// end class ListIterator
7
  • "next element" in what sence? Forward iteration or backward iteration? I believe you need a forward iteration here. Commented May 4, 2015 at 6:13
  • where is your line 51? Commented May 4, 2015 at 6:14
  • Yes, forward iteration, how do I accomplish that? And do I also need a backward method for the iterator? I'm still bit confused. Please help, thanks! Commented May 4, 2015 at 6:15
  • What is 'head' - your code snippet does not show such variable. Is the NPE thrown for the first call to 'next'? What is the dataset you insert to your list - give us more to analyze. Commented May 4, 2015 at 6:16
  • @Lrrr This is line 51: E value = current.item; Commented May 4, 2015 at 6:16

1 Answer 1

2

It seems your current object is null. Can you check it?

Sign up to request clarification or add additional context in comments.

5 Comments

Well, the class Deque is in-complete. It does not include most of the required methods to work as a proper dequeue. Maybe OP can check the algorithm here basicdatastructures.blogspot.in/2007/12/…
public Deque() { head = new Node(); tail = new Node(); head.next = tail; tail.prev = head; N = 0; }
Now it seems better. You should not get this exception now. :)
Sorry unfortunately I still get them, I suspect there must be something wrong with the E next method.
Where is your add() method which adds a new node in dequeue? Also, give complete stacktrace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.