linkedList.listIterator(linkedList.size()) 优化了吗?

Is linkedList.listIterator(linkedList.size()) optimized?

我正在尝试为 LinkedList 创建一个反向 ListIterator,并且打算将其实现为 linkedList.listIterator(linkedList.size()) 的包装器,交换 nextprevious 操作,但后来意识到,如果 LinkedList#listIterator(int) 实现只是向前遍历到指定的位置,使用它从末尾开始将是非常不优化的,必须遍历列表两次而不是一次,当列表支持直接到末尾时。 linkedList.listIterator(linkedList.size()) 是否优化为不遍历整个列表?

优化了,就在这里

private class ListItr implements ListIterator<E> {

...

ListItr(int index) {
    // assert isPositionIndex(index);
    next = (index == size) ? null : node(index);
    nextIndex = index;
}

...

Node<E> node(int index) {
    // assert isElementIndex(index);

    if (index < (size >> 1)) {  <-- if index less than half size go forward
        Node<E> x = first;
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {                     <-- otherwise backwards
        Node<E> x = last;
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}

ListIterator 使用索引来确定从哪个元素开始。 In the Oracle docs for LinkedList,它说:

All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.

因此,当您执行 linkedList.listIterator(linkedList.size()) 时,它将恰好向后遍历列表 0 步以获取正确的索引。因此,您可以说它已尽可能优化。继续包装那个迭代器。