简体   繁体   中英

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

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 ?

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