How is the implementation of LinkedHashMap different from HashMap?

前端 未结 8 1255
故里飘歌
故里飘歌 2020-12-28 12:07

If LinkedHashMap\'s time complexity is same as HashMap\'s complexity why do we need HashMap? What are all the extra overhead LinkedHashMap has when compared to HashMap in Ja

相关标签:
8条回答
  • 2020-12-28 12:57
    • Re-sizing is supposed to be faster as it iterates through its double-linked list to transfer the contents into a new table array.
    • containsValue() is Overridden to take advantage of the faster iterator.
    • LinkedHashMap can also be used to create a LRU cache. A special LinkedHashMap(capacity, loadFactor, accessOrderBoolean) constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently. In this case, merely querying the map with get() is a structural modification.
    0 讨论(0)
  • 2020-12-28 12:58

    HashMap does not maintains insertion order, hence does not maintains any doubly linked list.

    Most salient feature of LinkedHashMap is that it maintains insertion order of key-value pairs. LinkedHashMap uses doubly Linked List for doing so.

    Entry of LinkedHashMap looks like this:

      static class Entry<K, V> {
         K key;
         V value;
         Entry<K,V> next;
         Entry<K,V> before, after;        //For maintaining insertion order    
         public Entry(K key, V value, Entry<K,V> next){
             this.key = key;
             this.value = value;
             this.next = next;
         }
      }
    

    By using before and after - we keep track of newly added entry in LinkedHashMap, which helps us in maintaining insertion order.

    Before refer to previous entry and after refers to next entry in LinkedHashMap.

    For diagrams and step by step explanation please refer http://www.javamadesoeasy.com/2015/02/linkedhashmap-custom-implementation.html

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