Java EnumMap with Example

Java EnumMap is a Java Map that uses keys of a single enum type. EnumMap utilizes the inherent associative nature of arrays and is therefore the most efficient implementation of Map.  In a nutshell, EnumMap is a one-trick-pony designed to be used when the keys of your Map are constants and therefore can be made static and final.

Constructors of EnumMap

Unlike EnumSet which is abstract, EnumMap is a concrete class with three constructors. Two of the constructors follow from the special property of Maps described in the lesson on Java Map interface. The third constructor of EnumMap takes a class object to identify the enum whose constants will be used as a key. Note that a EnumMap does not have a no-args constructor because it does not make sense to create an EnumMap without specifying enum type.

  1. EnumMap(Class<K> keyType) -> Most frequently used constructor.  Creates an empty enum map with the specified key type.
  2. EnumMap(EnumMap<K,? extends V> m) -> The copy constructor, copies all entries from one enum to another.
  3. EnumMap(Map<K,? extends V> m) -> Creates an enum map initialized from the specified map.

Salient Features of EnumMap

There are a number of distinguishing features of EnumMap. EnumMap –

  1. Has a range of the universe of keys. Certain optimizations are possible since the number of keys in EnumMap is finite.
  2. Is an ordered map. The entries are stored in their ‘natural’ order, meaning they are stored in the order the keys are declared in the enum.
  3. Does not allow null keys. You can have null values.
  4. Has fail-fast iterators. This implies that under no circumstances will ConcurrentModificationException be thrown. HashMapTreeMap and LinkedHashMap have weakly consistent iterators.
  5. Is not thread safe as none of the methods are synchronized. If you need to use EnumMap in a multithreaded environment you have to use external locking constructs.
  6. Has much better performance than even HashMap, but can only be used if the keys are of the same enum type.

EnumMap Example

In the example below we consider a situation where we need to store and later display information about major social networks. Since the number of popular social networks is finite and each network is an entity in itself, we can model social networks as an enum.

Next, we put String descriptions for each social network in the EnumMap and later iterate. The complete code is shown below –

The output of the above program is shown below –

Having looked at HashMapTreeMap and EnumMap in this article we will now move on to examine LinkedHashMap.

Leave a comment

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