23k
23k

Reputation: 1399

Writing a ListIterator that mirrors Java's built in Iterator

So I'm attempting to mirror the functionality of Java's ListIterator. The only thing I'm having trouble wrapping my head around is getting the previous() method working correctly.

Here's what I have.

public ListIterator300<Item> listIterator() {

    return new ListIterator300<Item>() {

        private Node<Item> n = first;

            public boolean hasNext() {
                 return n.next != last;
            }

            public Item next() {
                n = n.next;
                return n.data;
            }

            public void remove() {
            }

            public boolean hasPrevious() {
               return n.previous != first;
            }

            public Item previous() {
                n = n.previous;
                return n.data;
            }
        };
    }

So, the issue I'm running into is having the previous() and next() methods, when called subsequently, return the same number. Now I've read that the built in ListIterator uses a cursor. Is there any general tips how I could implement this into my code?

For example

[1 2 3 4]

next() -> 1

previous() -> 1

next() -> 1

next() -> 2

Upvotes: 0

Views: 84

Answers (1)

Nir Alfasi
Nir Alfasi

Reputation: 53535

Instead of checking:

n.next != last;

check:

n != last;

and the same for:

n.previous != first;

replace it with:

n != first;

Do you see why ?

Upvotes: 1

Related Questions