EnumMap in Java

EnumMap in Java

EnumMap is specialized Map implementation designed and optimized for using Java Enum as key. EnumMap in Java is added on JDK  5 release. There are some similarities as well as differences between EnumMap and HashMap which you can find hereFollowings are the features of EnumMap.

  • All of the keys in an enum map must come from a single enum type that is specified at time of creation of EnumMap.
  • Enum maps are maintained in the natural order of their keys i.e the order in which the enum constants are declared.
  • Unlike HashMap, iterators of EnumMap are fail-save. they will never throw ConcurrentModificationException and they may or may not show the effects of any modifications to the map that occur while the iteration is in progress.
  • Null keys are not permitted, EnumMap throws NullPointerException while trying to enter null as key. However null values are permitted in EnumMap.
  • EnumMap is not synchronized. It should synchronize manually in case you want to use it in multithreading environment. We can use Collections.synchronizedMap() method to synchronize EnumMap.
  • Performance of EnumMap is better than their counter part HashMap.

EnumMap provides following constructors.

[table “” not found /]

Example of EnumMap

Output

 

 

Leave a Reply

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