i think HashMap also provides O(1) for deletion
That's true, but HashMap
doesn't have to maintain the order of the keys. Therefore, when removing an entry, it only has to modify the small linked list of the bucket from which the entry is removed (in the pre-Java 8 implementation. The Java 8 implementation uses trees), which should take expected O(1)
time.
LinkedHashMap
, on the other hand, has to maintain the order in which the keys were added to the Map, which it does with an additional linked list that contains all the entries of the Map. Therefore, when you remove an entry, if you don't have access to the previous entry in this big linked list, you'll have to iterate over the linked list from its beginning until you find it, which will require linear time.
You can see what LinkedHashMap
does after removing an entry here :
void afterNodeRemoval(Node<K,V> e) { // unlink
LinkedHashMap.Entry<K,V> p =
(LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
p.before = p.after = null;
if (b == null)
head = a;
else
b.after = a;
if (a == null)
tail = b;
else
a.before = b;
}
This couldn't be done in constant time with a singly linked list.