EnumMap in Java

In Java, EnumMap is a specialized implementation of the Map interface that is designed for use with enum keys. It provides a high-performance and type-safe implementation of a map that is specifically tailored to work with enum keys. This makes it a useful tool for any application that requires the use of enums as keys in a map.

EnumMap in Java


The EnumMap class in Java was introduced in JDK 5 as part of the Java Collections Framework. It is a specialized implementation of the Map interface that is designed to work specifically with enum keys. Unlike a regular HashMap or TreeMap, which can use any object as a key, an EnumMap can only use enum constants as keys.

One of the key advantages of using an EnumMap is that it provides a highly optimized implementation of a map for enum keys. Since the map is built specifically for use with enums, it can take advantage of the fact that the number of enum constants is known in advance, and optimize its implementation accordingly. This results in faster and more efficient performance compared to using a regular HashMap or TreeMap.

Creating an EnumMap


To create an EnumMap in Java, you first need to define the enum type that will be used as the key. Once you have defined the enum type, you can create an EnumMap by passing the enum class as a parameter to the EnumMap constructor. Here is an example:

enum Color {
RED, GREEN, BLUE
}

Map colorMap = new EnumMap<>(Color.class);


In this example, we have defined an enum type called Color, and then created an EnumMap that uses Color as its key type.

Adding and Retrieving Values


You can add values to an EnumMap using the put() method, and retrieve values using the get() method. Here is an example:

colorMap.put(Color.RED, "FF0000");
colorMap.put(Color.GREEN, "00FF00");
colorMap.put(Color.BLUE, "0000FF");

String redValue = colorMap.get(Color.RED); // returns "FF0000"


Iterating over an EnumMap


You can iterate over the entries in an EnumMap using a for-each loop or an iterator. Since the keys are enum constants, you can use the values() method of the enum type to get an array of all the enum constants. Here is an example:

for (Color color : Color.values()) {
String value = colorMap.get(color);
System.out.println(color + " -> " + value);
}


Output:

RED -> FF0000
GREEN -> 00FF00
BLUE -> 0000FF


Conclusion


EnumMap in Java is a powerful and optimized implementation of the Map interface that is designed specifically for use with enum keys. It provides type-safety and high-performance, making it a useful tool for any application that requires the use of enums as keys in a map. The EnumMap class is part of the Java Collections Framework and is available in JDK 5 and above.