4

I know my question is very much similar to one which are posted previously.I have gone through multiple post for this but still not very much clear with the answer.That's why i am posting it again.

Why Linked HashMap uses doubly LinkedList over Single LinkedList while order can also be maintained through Single LinkedList.

In answers of some of the previous post it was mentioned that LinkedHashMap provides O(1) complexity for deletion because it has previous as well as next element pointer but i think HashMap also provides O(1) for deletion.

Thanks,

Manish
  • 1,274
  • 3
  • 22
  • 59

1 Answers1

7

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.

Eran
  • 387,369
  • 54
  • 702
  • 768