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
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.