I was following a previous post on this that says:
For LinkedList
- get is O(n)
- add is O(1)
- remove is O(n)
This is a bad benchmark IMO.
ArrayList resizes, which is costly. If you had constructed ArrayList as new ArrayList(500000) you would construct in one blow, and then all allocations would be quite cheap (one preallocating backed array)list.get you will find linkedlists are awful for grabbing anything other than the first or last element. For an arraylist: the jdk get is what you'd expect:
public E get(int index) {
RangeCheck(index);
return elementData[index];
}
(basically just return the indexed array element.,
For a linkedlist:
public E get(int index) {
return entry(index).element;
}
looks similar? Not quite. entry is a method not an primitive array, and look what it has to do:
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;
}
That's right, if you ask for say list.get(250000), it's gotta start at the head and repeatedly iterate through the next element. 250000 accesses or so (there's an optimization in the code where it starts at head or tail depending on which would be less accesses.)