Is Java's LinkedList optimized to do get(index) in reverse when necessary?

笑着哭i 提交于 2019-12-04 01:26:46

问题


I've been working on some ways to optimize LinkedList's. Does anyone know if the Java default doubly-linked LinkedList class is optimized to do get() operations in reverse? For example:

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

Would the call to list.get(half + 1) optimize the search and go in reverse since it is a doubly-linked list? It would make more sense to do the search from the end and go towards the center if you know the element is in the second half of the list.

I know using get(index) is O(n) time and that you should use an iterator when traversing a LinkedList, but I am just curious.


回答1:


Yes it is. You can inspect the source code yourself: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/LinkedList.java#LinkedList.entry%28int%29

LinkedList#get(int) is implemented as just

return entry(index).element;

where entry is a private method. entry's definition is:

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

As you can see, it counts down from the end if index is greater than the midpoint of the list.



来源:https://stackoverflow.com/questions/19151841/is-javas-linkedlist-optimized-to-do-getindex-in-reverse-when-necessary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!