Java Util EnumMap



Introduction

The Java EnumMap class is a specialized Map implementation for use with enum keys. The EnumMap class is part of the Collections Framework in Java.

The Enum maps are implemented as arrays internally, which makes this implementation very efficient and compact. It is a high-performance map implementation and is faster than HashMap.

The EnumMap does not allow Null keys, and will throw a NullPointerException error if we try to insert a null key. However, Null values are allowed in the EnumMap class.

Characterstics

The following are the important points about EnumMap −

  • All of the keys in an enum map must come from a "single enum type" that is specified, explicitly or implicitly, when the map is created.
  • Enum maps are maintained in the natural order of their keys.
  • EnumMap is not synchronized. If multiple threads access an enum map concurrently, and at least one of the threads modifies the map, it should be synchronized externally.

Class Declaration

The following is the declaration for java.util.EnumMap class −

public class EnumMap<K extends Enum<K>,V>
   extends AbstractMap<K,V>
   implements Serializable, Cloneable

Parameters

  • K − The type of keys maintained by this map(eg, Day).
  • V − The type of mapped values (eg, Monday, Tuesday).

Why do we need an EnumMap Class?

Suppose we have a basic need where we have to map days of the week with the subject we have to study on that day −

MONDAY     Mathematics
TUESDAY    Physics
WEDNESDAY  Chemistry
THURSDAY   Computer Science
FRIDAY     English

Then, to organize the above needs, we can use an EnumMap as per the requirements, like here we have days of the week, which will be later used as the keys for our map −

public enum Days_Of_Week {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

Creating an EnumMap

To create an EnumMap class, first we need to import the java.util.EnumMap or java.util.* package. Then we need to create an object of it to initialize it.

Syntax

Below is the syntax for initializing an EnumMap in Java −

EnumMap<Days_Of_Week, String> subject = new EnumMap<>(Days_Of_Week.class);

Above the Days_Of_Week is the key of the enum that maps to values, and strings are the values of the enum map associated with the corresponding keys.

Example

Below is an example of creating an EnumMap in Java −

package com.tutorialspoint;

import java.util.EnumMap;

public class EnumMapDemo {

   // creating an enum for the EnumMap 
   public enum Days_Of_Week { 
      MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY 
   }

   public static void main(String[] args) {
      // creating an EnumMap with Days_Of_Week as keys and String as values
      EnumMap<Days_Of_Week, String> subject = 
         new EnumMap<>(Days_Of_Week.class);

      // associate values in map
      subject.put(Days_Of_Week.MONDAY, "Mathematics");
      subject.put(Days_Of_Week.TUESDAY, "Physics");
      subject.put(Days_Of_Week.WEDNESDAY, "Chemistry");
      subject.put(Days_Of_Week.THURSDAY, "Computer Science");
      subject.put(Days_Of_Week.FRIDAY, "English");

      // print the whole map
      System.out.println(subject); 
   }
}

Let us compile and run the above program. This will produce the following result −

{MONDAY=Mathematics, TUESDAY=Physics, WEDNESDAY=Chemistry, 
   THURSDAY=Computer Science, FRIDAY=English}

Class Constructors

The following are the class constructors supported by the EnumMap in Java −

Sr.No. Constructor & Description
1

EnumMap(Class<K> keyType)

This constructor creates an empty enum map with the specified key type.

2

EnumMap(EnumMap<K,? extends V> m)

This constructor creates an enum map with the same key type as the specified enum map, initially containing the same mappings (if any).

3

EnumMap(Map<K,? extends V> m)

This constructor creates an enum map initialized from the specified map.

Class Methods

The following are the class methods supported by the EnumMap in Java −

Sr.No. Method & Description
1 void clear()

This method removes all mappings from this map.

2 EnumMap<K,V> clone()

This method returns a shallow copy of this enum map.

3 boolean containsKey(Object key)

This method returns true if this map contains a mapping for the specified key.

4 boolean containsValue(Object value)

This method returns true if this map maps one or more keys to the specified value.

5 Set<Map.Entry<K,V>> entrySet()

This method returns a Set view of the mappings contained in this map.

6 boolean equals(Object o)

This method compares the specified object with this map for equality.

7 V get(Object key)

This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

8 int hashCode()

This method returns the hash code value for this map.

9 Set<K> keySet()

This method returns a Set view of the keys contained in this map.

10 V put(K key, V value)

This method associates the specified value with the specified key in this map.

11 void putAll(Map<? extends K,? extends V> m)

This method Copies all of the mappings from the specified map to this map.

12 V remove(Object key)

This method removes the mapping for this key from this map if present.

13 int size()

This method returns the number of key-value mappings in this map.

14 Collection<V> values()

This method returns a Collection view of the values contained in this map.

Methods inherited

This class inherits methods from the following classes −

  • java.util.AbstractMap
  • java.util.Object

Adding a Key-Value to an EnumMap

The following example shows the usage of Java EnumMap put(K,V) method to put a value in the EnumMap instance. We've created a enum Numbers. Then EnumMap is created of enum Numbers and Integer. Few entries are added using put(K,V) and enumMap is printed. Using put() method again, a value of enumMap is replaced and map is printed again.

package com.tutorialspoint;

import java.util.EnumMap;

public class EnumMapDemo {
   
   // create an enum
   public enum Numbers{ONE, TWO, THREE, FOUR, FIVE}; 

   public static void main(String[] args) {
      
      EnumMap<Numbers,Integer> map = 
         new EnumMap<>(Numbers.class);

      // associate values in map
      map.put(Numbers.ONE, 1);
      map.put(Numbers.TWO, 2);
      map.put(Numbers.THREE,3);

      // print the whole map
      System.out.println(map); 

      map.put(Numbers.THREE, 4);
	  
      // print the updated map
      System.out.println(map);
   }
}

Let us compile and run the above program. This will produce the following result −

{ONE=1, TWO=2, THREE=3}
{ONE=1, TWO=2, THREE=4}
Advertisements