Saturday, August 4, 2012
Difference between HashMap and LinkedHashMap in Java
Difference between LinkedHashMap and HashMap in Java
HashMap and LinkedHashMap are two
most common used Map implementation in Java and main difference between HashMap and LinkedHashMap is that
LinkedHashMap maintain insertion order of keys, Order in which keys are inserted in to
LinkedHashMap. On the other hand HashMap doesn't
maintain any order or keys or values. In terms of Performance there is not much
difference between HashMap and LinkedHashMap but yes
LinkedHashMap has more memory foot print than HashMap to
maintain doubly LinkedList which it uses to keep track of insertion order of
and HashMap in Java - Similarities
There are lot of similarity between LinkedHashMap and HashMap in Java,
as they both implement Map interface.
let's have a look :
1) Both LinkedHashMap and HashMap are not
synchronized and subject to race condition if shared between multiple threads
without proper synchronization. Use Collections.synchronizedMap() for making
2) Iterator returned by HashMap and LinkedHashMap are
fail-fast in nature.
3) Performance of HashMap and LinkedHashMap are
Difference between LinkedHashMap and
HashMap in Java
Now let's see some differences between LinkedHashMap and HashMap in Java:
1) First and foremost difference between LinkedHashMap and HashMap is order, HashMap doesn't
maintain any order while LinkedHashMapmaintains insertion order
of elements in Java.
2) LinkedHashMapalso requires more memory than HashMap because of
this ordering feature. As I said before LinkedHashMapuses
doubly LinkedList to keep order of elements.
3) LinkedHashMapactually extends HashMap and
implements Map interface.
Given the insertion order guarantee of LinkedHashMap, Its a
good compromise between HashMap and TreeMap in Java
because with TreeMap you get increased cost of
iteration due to sorting and performance drops on to log(n) level from