Difference between HashMap and LinkedHashMap in Java with Example

HashMap and LinkedHashMap are common implementation of Map.The main difference between HashMap and LinkedHashMap is that LinkedHashMap maintains insertion order of keys, order in which keys are inserted to LinkedHashMap while HashMap does not maintain any order of keys.
In this post we will share the similarities, differences between HashMap and LinkedHashMap along with examples.

Difference between HashMap and LinkedHashMap

1. Insertion order :  HashMap does not maintain the order while LinkedHashMap maintains the insertion order of elements in java.

2. Memory : The second difference between HashMap and LinkedHashMap is memory. LinkedHashMap requires more memory than HashMap because of the ordering feature. Internally LinkedHashMap uses doubly Linked List to maintain order of elements.

3. Inheritance :  LinkedHashMap extends HashMap and implements Map interface while HashMap implements Map interface.

Similarities between HashMap and LinkedHashMap

1. Iterator returned by both HashMap and LinkedHashMap are fail-fast in nature.

2. Both HashMap and LinkedHashMap are similar in terms of performance.

3. LinkedHashMap and HashMap are not synchronized and subject to race condition if shared between multiple threads without proper synchronization.

Important Points to Note about LinkedHashMap

1.  Reentering a value does not change the insertion order of the LinkedHashMap. For example,
if you already have a key and you want to update its value by using put(key, newValue) , the insertion order of the LinkedHashMap will remain the same.

2. LRU(Least Recently Used) cache can be created by the use of the LinkedHashMap. Since in LRU cache, oldest  non accessed entry is removed, which is the head of the doubly linked list maintained by LinkedHashMap.

3. Iterator of LinkedHashMap returns element in the insertion order or access order.

4. There is a protected method called removeEldestEntry() whose default implementation return false. If the method is overridden ,an implementation can return true to remove oldest entry, when a new entry is added.

That's all about difference between HashMap and LinkedHashMap in java.

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry