EnumMap in Java

Posted on Updated on

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.

Constructor Description
EnumMap(Class keyType) Creates an empty enum map with the specified key type. Throws NullPointerException if keyType is null.
EnumMap(EnumMap m) Creates an enum map with the same key type as the specified enum map, initially containing the same mappings. Throws NullPointerException if m is null.
EnumMap(Map m) Creates an enum map initialized from the specified map. If the specified map is an EnumMap instance, this constructor behaves identically to EnumMap. Otherwise, the specified map must contain at least one mapping. Throws NullPointerException if m is null and IllegalArgumentException if m is not an EnumMap instance and contains no mappings.

Example of EnumMap




Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.