EnumMap in Java is a concrete class that provides Map implementation whose keys are of the enum type.
All the keys in the EnumMap must originate from a single enum type that is specified, implicitly or explicitly, when the map is created.
Enum maps are represented internally as an array to hold the corresponding values that are extremely compact and efficient.
EnumMap in Java was added in Java 5.0 version and present in java.util.EnumMap package.
Hierarchy of EnumMap class in Java
Java EnumMap class extends AbstractMap class and implements Map, Serializable and Cloneable interfaces. The hierarchy diagram of EnumMap in Java is shown in the below diagram.
EnumMap class declaration
EnumMap is a generic class that is a subclass of the Enum class. Generally, It can be declared as:
public class EnumMap<K extends Enum<K>,V> extends AbstractMap<K,V> implements Serializable, Cloneable
EnumMap accepts two parameters as K and V where K defines the type of Keys that extends Enum class and V defines the type of Values.
Features of EnumMap in Java
There are many important features of enum map in java that are as follows:
1. EnumMap is a Map implementation that is used with keys of enumerated type.
2. Null keys are not permitted in the enum map but null values are permitted. Any attempt to store a null key will throw a named NullPointerException because an enum map is represented internally as an array in the terms of performance.
3. Java EnumMap maintains the natural order of their keys in which the enum constants are declared.
4. EnumMap is not synchronized in java. That means it is not thread-safe. Multiple threads can access the same enum map object concurrently.
To synchronize it, use synchronizedMap method of the Collections class. The syntax is given below:
Map<EnumKey, V> map = Collections.synchronizedMap(new EnumMap<EnumKey, V>(...)); For example: Map<Days, String> map = Collections.synchronizedMap(new EnumMap<Days, String>(daysEnumMap));
5. The iterators returned by the collections views (keySet(), entrySet(), and values()) are weakly consistent. They will never throw ConcurrentModificationException and they may or may not show the effects of any modifications to the map that occur while during iteration.
Constructors of EnumMap class
Java EnumMap class defines the following constructors. They are as follows:
1. EnumMap(Class<K> keyType): This form of constructor creates an empty enum map with the specified keyType. This constructor will throw NullPointerException when keyType is a null reference.
2. EnumMap(EnumMap em): This form of constructor constructs an enum map with the same key type as the specified enum map em. It will throw NullPointerException when em contains the null reference.
3. EnumMap(Map m): This constructor constructs an enum map that is initialized from the specified map m. If the map m is an enum map then this constructor will behave the same manner as the second constructor.
If the map m is not an enum map, it must have at least one mapping (key-value pairs). It is essential to determine the key type of constructed enum map.
EnumMap Methods in Java
Following methods are defined by EnumMap class in Java.
1. void clear(): It removes all the key-value pairs from the 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 key-value pair for the specified key.
4. boolean containsValue(Object value): It returns true if the map maps one or more keys to the specified value.
5. Set<Map.Entry<K,V>> entrySet(): This method returns a collection or set view of the key-value pairs (mappings) contained in this map.
6. boolean equals(Object o): It compares the specified object with this map for equality.
7. V get(Object key): It is used to receive the value to which the specified key is mapped, or null if this map contains no mapping for the key.
8. int hashCode(): It is used to receive the hash code value for this map.
9. Set<K> keySet(): This method returns a collection view of the keys contained in this map.
10. V put(K key, V value): It is used to add the specified value associated with the specified key in this map.
11. void putAll(Map m): This method copies all of the key-value pairs from the specified map to this map.
12. V remove(Object key): It is used to remove a key-value pair (mapping) for the given key from the map if present.
13. int size(): It returns the number of key-value mappings in this map.
14. Collection<V> values(): It returns a set view of the values contained in this map.
Methods inherited from class AbstractMap: isEmpty, toString
Methods inherited from Object class: finalize, getClass, notify, notifyAll, wait
Methods inherited from Map interface: compute, computeIfAbsent, computeIfPresent, forEach, getOrDefault, merge, putIfAbsent, remove, replace, replaceAll
Java EnumMap Example Programs
Let’s take an example program based on the methods of enum map in java. Look at the source code.
Program source code 1:
import java.util.EnumMap; public class EnumMapEx { public enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday; } public static void main(String[] args) { // Create a EnumMap. EnumMap<Days, String> enmap = new EnumMap<Days, String>(Days.class); // Adding entries in enum map. enmap.put(Days.Monday, "Day 2"); enmap.put(Days.Tuesday, "Day 3"); enmap.put(Days.Sunday, "Day 1"); enmap.put(Days.Wednesday, "Day 4"); enmap.put(Days.Saturday, "Day 7"); enmap.put(Days.Thursday, "Day 5"); enmap.put(Days.Friday, "Day 6"); System.out.println("Entries of enum map: " +enmap.entrySet()); System.out.println("Keys of enum map: " +enmap.keySet()); System.out.println("Values of enum map: " +enmap.values()); System.out.println("Is key Sunday present in enum map: " +enmap.containsKey(Days.Sunday)); System.out.println("Is value Day 3 present in enum map: " +enmap.containsValue("Day 3")); Object getDay = enmap.get(Days.Saturday); System.out.println("Value of Saturday: " +getDay); } }
Output: Entries of enum map: [Sunday=Day 1, Monday=Day 2, Tuesday=Day 3, Wednesday=Day 4, Thursday=Day 5, Friday=Day 6, Saturday=Day 7] Keys of enum map: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday] Values of enum map: [Day 1, Day 2, Day 3, Day 4, Day 5, Day 6, Day 7] Is key Sunday present in enum map: true Is value Day 3 present in enum map: true Value of Saturday: Day 7
Explanation:
1. In this program, we have created a class EnumMapEx. Inside the EnumMapEx class, we have created inner class Days of type enum.
2. The EnumMap enmap is constructed inside the main method by using the first constructor and passing the Class of Days enum. The keys are of the type Days. The values are of the type String.
3. The methods entrySet(), keySet(), and values() return a set view of the entries, keys, and a collection view of values, respectively.
4. As you can see in the output of the above program, the ordering of keys is according to the ordering of enum Days.
How to Iterate EnumMap in Java?
In this section, we will iterate over keys, values, and entries of the enum map. We will also remove a key during iteration. Look at the source code to understand better.
Program source code 2:
import java.util.EnumMap; import java.util.Iterator; import java.util.Map.Entry; public class IteratingEnumMap { public enum CartoonCharacter { Archie, Sabrina, Tom, Jerry, Mickey, Richie; } public static void main(String[] args) { EnumMap<CartoonCharacter, String> enmap = new EnumMap<CartoonCharacter, String>(CartoonCharacter.class); enmap.put(CartoonCharacter.Archie, "Main hero"); enmap.put(CartoonCharacter.Sabrina, "Teenager"); enmap.put(CartoonCharacter.Jerry, "Mouse"); enmap.put(CartoonCharacter.Tom, "Cat"); enmap.put(CartoonCharacter.Richie, "Richest kid"); enmap.put(CartoonCharacter.Mickey, "Mouse"); System.out.println("Iterating keys of enum map"); Iterator<CartoonCharacter> keySet = enmap.keySet().iterator(); while(keySet.hasNext()){ Object key = keySet.next(); System.out.println(key); } System.out.println("\n"); System.out.println("Iterating values in enum map"); Iterator<String> values = enmap.values().iterator(); while(values.hasNext()){ System.out.println(values.next()); } System.out.println("\n"); System.out.println("Iterating entries in enum map"); Iterator<Entry<CartoonCharacter,String>> entrySet = enmap.entrySet().iterator(); while(entrySet.hasNext()){ Object eSet = entrySet.next(); System.out.println(eSet); } // Call remove() method to remove entry for specified key from enum map and returns value associated with specified key. System.out.println("Value associated with removing key: " +enmap.remove(CartoonCharacter.Mickey)); } }
Output: Iterating keys of enum map Archie Sabrina Tom Jerry Mickey Richie Iterating values in enum map Main hero Teenager Cat Mouse Mouse Richest kid Iterating entries in enum map Archie=Main hero Sabrina=Teenager Tom=Cat Jerry=Mouse Mickey=Mouse Richie=Richest kid Value associated with removing key: Mouse
Hope that this tutorial has covered almost all important points related EnumMap in Java with example programs. I hope that you will have understood this topic.
Thanks for reading!!!
Next ⇒ SortedMap in Java