How is the internal implementation of LinkedHashMap different from HashMap implementation?

后端 未结 5 1411
忘了有多久
忘了有多久 2020-12-12 21:04

I read that HashMap has the following implementation:

main array 
   ↓
[Entry] → Entry → Entry      ← linked-list implementation
[Entry]
[Entry] → Entry
[Ent         


        
5条回答
  •  生来不讨喜
    2020-12-12 21:39

    HashMap does not maintain insertion order, hence it does not maintain 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 key;
         V value;
         Entry next;
         Entry before, after;        //For maintaining insertion order    
         public Entry(K key, V value, Entry 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 refers to previous entry and after refers to next entry in LinkedHashMap.

    LinkedHashMap

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

    Thanks..!!

提交回复
热议问题