【问题标题】:Is Java's LinkedList optimized to do get(index) in reverse when necessary?Java 的 LinkedList 是否经过优化以在必要时反向执行 get(index)?
【发布时间】:2013-10-03 05:59:18
【问题描述】:

我一直在研究一些优化 LinkedList 的方法。有谁知道 Java 默认的双向链接 LinkedList 类是否经过优化以反向执行 get() 操作? 例如:

// Some LinkedList list that exists with n elements;
int half = list.size() / 2;
list.get(half + 1);

调用list.get(half + 1) 是否会优化搜索并反向进行,因为它是一个双向链表?如果您知道该元素位于列表的后半部分,那么从末尾进行搜索并朝着中心进行搜索会更有意义。

我知道使用 get(index)O(n) 时间,并且您应该在遍历 LinkedList 时使用迭代器,但我只是好奇。

【问题讨论】:

  • 就在 javadocs 的第三段(Java 7 中的第二段):Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
  • 请注意,从性能POV来看,LinkedList的大多数使用无论如何都是错误的。

标签: java performance data-structures linked-list


【解决方案1】:

是的。您可以自己查看源代码:http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/LinkedList.java#LinkedList.entry%28int%29

LinkedList#get(int) 被实现为just

return entry(index).element;

其中entry 是私有方法。 entry的定义是:

private Entry<E> entry(int index) {
    if (index < 0 || index >= size)
        throw new IndexOutOfBoundsException("Index: "+index+
                                            ", Size: "+size);
    Entry<E> e = header;
    if (index < (size >> 1)) {
        for (int i = 0; i <= index; i++)
            e = e.next;
    } else {
        for (int i = size; i > index; i--)
            e = e.previous;
    }
    return e;
}

如您所见,如果 index 大于列表的中点,则从末尾开始倒计时。

【讨论】:

    猜你喜欢
    • 2017-04-01
    • 2020-04-02
    • 1970-01-01
    • 2020-05-12
    • 2016-07-05
    • 2019-06-27
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多