简体   繁体   English

编写一个反映Java内置Iterator的ListIterator

[英]Writing a ListIterator that mirrors Java's built in Iterator

So I'm attempting to mirror the functionality of Java's ListIterator . 因此,我试图镜像Java的ListIterator的功能。 The only thing I'm having trouble wrapping my head around is getting the previous() method working correctly. 我束手无策的唯一困难是使previous()方法正确工作。

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. 因此,我遇到的问题是具有previous()next()方法,随后被调用时,它们返回相同的数字。 Now I've read that the built in ListIterator uses a cursor. 现在,我已阅读到内置的ListIterator使用游标。 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 ? 你明白为什么吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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