简体   繁体   中英

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;}
            }

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(); } } 

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM