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

前端 未结 1 999
独厮守ぢ
独厮守ぢ 2021-01-13 11:41

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() operatio

1条回答
  •  醉梦人生
    2021-01-13 11:56

    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 entry(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);
        Entry 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.

    0 讨论(0)
提交回复
热议问题