简体   繁体   English

是否已优化linkedList.listIterator(linkedList.size())?

[英]Is linkedList.listIterator(linkedList.size()) optimized?

I'm trying to create a reverse ListIterator for a LinkedList , and was going to just implement it as a wrapper to linkedList.listIterator(linkedList.size()) that swaps the next and previous operations, but then realized that if LinkedList#listIterator(int) is implemented to just traverse forwards to the position specified, using it to start at the end would be terribly unoptimized, having to traverse the list twice rather than once, when the list supports going directly to the end. 我正在尝试为LinkedList创建反向ListIterator ,并打算将其实现为对linkedList.listIterator(linkedList.size())的包装,从而交换nextprevious操作,但随后意识到,如果LinkedList#listIterator(int)被实现为仅向前移动到指定的位置,使用它从末尾开始将是完全没有优化的,当列表支持直接到末尾时,必须遍历列表两次而不是一次。 Is linkedList.listIterator(linkedList.size()) optimized to not traverse the entire list? 是否已优化linkedList.listIterator(linkedList.size())以不遍历整个列表?

A ListIterator uses indexes to identify which element to start at. ListIterator使用索引来标识从哪个元素开始。 In the Oracle docs for LinkedList , it says: 在Oracle的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. 索引到列表中的操作将从开头或结尾遍历列表,以更接近指定索引的位置为准。

Thus when you do linkedList.listIterator(linkedList.size()) , it will traverse the list backwards exactly 0 steps to grab the correct index. 因此,当您执行linkedList.listIterator(linkedList.size()) ,它将向后精确地向后遍历列表0个步骤以获取正确的索引。 So, you could say that it's as optimized as it possibly can be. 因此,您可以说它已尽可能优化。 Go ahead and wrap that iterator. 继续并包装该迭代器。

It is optimized, it's here 经过优化,在这里

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;
    }
}

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

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