HashMap vs EnumMap

Posted on Updated on

EnumMap was introduced in Java along with JDK 5 updates which is specialized Map implementation designed and optimized for using Java Enum as key. Java is having HashMap and lots of other concrete implementation of Map interface. So it is natural to ask question around EnumMap and other maps in interview. Most popular in all of these are HashMap vs EnumMap. Here we will be discussing differences and similarities of these two maps.

Differences between EnumMap and HashMap.

EnumMap HashMap
EnumMap is specialized Map implementation designed and optimized for using Java Enum as key. HashMap is not specialized Map, we can store any object as key.
Enum maps are maintained in the natural order of their keys. Order is not maintained in HashMap.
Iterators of EnumMap is fail-save. Iterators of HashMap is fail-fast.
Null is not permitted as key in EnumMap. One null key is permitted as key in HashMap.
Performance of EnumMap is better as compare to HashMap. Performance of HashMap slightly less as compare to EnumMap.

Similarities between EnumMap and HashMap.

  1. Both EnumMap and HashMap allow null as valid value.
  2. Both these maps are not synchronized. We should manually synchronize both these map in case of multithreading environment.

Click here to understand more about EnumMap.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.