ListIterator 在交替调用 next() 和 previous() 时重复元素

ListIterator repeating elements on alternate calls of next() and previous()

我写了下面的程序来迭代列表,但是在交替遍历时 next() and previous() 它重复了元素。我通过在我的打印逻辑之前放置一个指示器并将其用于 extra nextextra previous 来知道修复方法。但我想知道为什么行为是这样的以及迭代器工作背后的算法是什么。

我已经检查了 java文档,它的写法是这样的,

next
Returns the next element in the list. This method may be called repeatedly to iterate through the list, or intermixed with calls to previous to go back and forth. (Note that alternating calls to next and previous will return the same element repeatedly.)

但问题是为什么?这样做的逻辑或目的是什么?

public class IterateLinkedListUsingListIterator {

public static void main(String[] args) throws NumberFormatException,
        IOException {
    LinkedList lList = new LinkedList();

    lList.add("1");
    lList.add("2");
    lList.add("3");
    lList.add("4");
    lList.add("5");

    ListIterator itr = lList.listIterator();
    boolean ch = true;

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (ch) {
        System.out.println("Enter choice");
        int chi = Integer.parseInt(br.readLine());
        switch (chi) {
        case 1:
            if (itr.hasNext()) {
                System.out.println(itr.next());
            }
            break;
        case 2:

            if (itr.hasPrevious()) {
                System.out.println(itr.previous());
            }
            break;

        default:
            ch = false;
        }

    }

}

}

as per @vincrichaud answer and java doc statement cursor points in between the element not on the element,为什么会这样?有什么具体原因吗。

                     Element(0)   Element(1)   Element(2)   ... Element(n-1)
cursor positions:  ^            ^            ^            ^                  ^

doc

中所述

Next Returns the next element in the list and advances the cursor position.

Previous Returns the previous element in the list and moves the cursor position backwards.

不明显的是光标位置总是在元素之间而不是在元素上。文档中也有描述。

A ListIterator has no current element; its cursor position always lies between the element

所以知道这一点,很明显,当您交替调用 next()previous() 时,您将获得相同的元素。

LinkedList lList = new LinkedList();
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
//lList look like [1,2,3,4,5]
ListIterator itr = lList.listIterator(); //create iterator at position before element 0

itr.next() // return the next element => so return "1"
           // And advance the cursor position => position between element 0 and element 1

itr.previous(); // return the previous element => so return "1"
           // And step back the cursor position => position before element 0