Java EnumMap
In Java, the EnumMap
class is a specialized Map implementation that is specifically designed for use with enums as keys. It provides a more efficient way of handling enum-based mappings than other Map implementations, such as HashMap
or TreeMap
, when dealing with enum types as keys.
Since enums are constants that belong to a specific type, EnumMap
takes advantage of this type-safety and performance characteristics to offer a faster and more memory-efficient solution. In this article, we'll explore how EnumMap
works, its benefits, and when you should use it in your Java applications.
EnumMap
is a Map implementation that specifically maps enum constants to values. It is part of the java.util
package and provides a high-performance, type-safe, and efficient way of associating enum keys with values.
Key features of EnumMap
:
HashMap
or TreeMap
when dealing with enums.EnumMap
must be of the enum type, ensuring type safety at compile time.EnumMap
internally uses an array to store the values, making it more memory-efficient than other map implementations.EnumMap
is the natural order of the enum constants (i.e., the order they are declared in the enum).The EnumMap
class provides a constructor to create an enum map based on the enum type of the keys:
EnumMap(Class<K> keyType) // Creates an empty EnumMap with the specified enum class as the key type.
EnumMap(EnumMap<? extends K, ? extends V> m) // Creates an EnumMap with the same mappings as the specified EnumMap.
EnumMap(Map<? extends K, ? extends V> m) // Creates an EnumMap from the given map if its keys are of the enum type.
EnumMap
supports most of the standard Map interface methods, but with optimizations for enum keys:
put(K key, V value)
: Adds a key-value pair to the map.
map.put(Day.MONDAY, "Start of the week");
get(Object key)
: Retrieves the value associated with the specified key.
String description = map.get(Day.MONDAY); // Returns "Start of the week"
containsKey(Object key)
: Checks if the map contains the specified key.
boolean exists = map.containsKey(Day.MONDAY); // Returns true if "MONDAY" is a key
remove(Object key)
: Removes the key-value pair associated with the specified key.
map.remove(Day.MONDAY); // Removes the entry with the key "MONDAY"
keySet()
: Returns a set view of all the keys in the map.
Set<Day> keys = map.keySet(); // Returns a Set of all enum keys
values()
: Returns a collection view of all the values in the map.
Collection<String> values = map.values(); // Returns a Collection of all values
clear()
: Removes all key-value pairs from the map.
map.clear(); // Clears the map
Here’s an example to demonstrate the basic usage of EnumMap
with enum constants as keys:
import java.util.EnumMap;
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class EnumMapExample {
public static void main(String[] args) {
// Create an EnumMap with enum Day as keys and String as values
EnumMap<Day, String> map = new EnumMap<>(Day.class);
// Add some key-value pairs
map.put(Day.MONDAY, "Start of the week");
map.put(Day.WEDNESDAY, "Midweek");
map.put(Day.FRIDAY, "End of the week");
// Access values using keys
System.out.println("Monday: " + map.get(Day.MONDAY)); // Output: Start of the week
System.out.println("Wednesday: " + map.get(Day.WEDNESDAY)); // Output: Midweek
System.out.println("Friday: " + map.get(Day.FRIDAY)); // Output: End of the week
// Print all the keys and values
System.out.println("All days: ");
for (Day day : map.keySet()) {
System.out.println(day + ": " + map.get(day));
}
}
}
Output:
Monday: Start of the week
Wednesday: Midweek
Friday: End of the week
All days:
MONDAY: Start of the week
WEDNESDAY: Midweek
FRIDAY: End of the week
In this example:
Day
with seven constants representing the days of the week.EnumMap
that maps each day to a description.put()
, get()
, and keySet()
methods to store and access values.EnumMap
allows you to easily iterate over the keys and values in the order of the enum constants. Here’s an example:
import java.util.EnumMap;
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class EnumMapIteration {
public static void main(String[] args) {
// Create an EnumMap
EnumMap<Day, String> map = new EnumMap<>(Day.class);
// Add some key-value pairs
map.put(Day.MONDAY, "Start of the week");
map.put(Day.TUESDAY, "Second day");
map.put(Day.WEDNESDAY, "Midweek");
// Iterate over the EnumMap using a for-each loop
for (Day day : map.keySet()) {
System.out.println(day + ": " + map.get(day));
}
}
}
Output:
MONDAY: Start of the week
TUESDAY: Second day
WEDNESDAY: Midweek
In this case, the iteration order follows the order in which the enum constants are defined (i.e., MONDAY
, TUESDAY
, WEDNESDAY
).
put()
, get()
, and remove()
is O(1). However, EnumMap
is specifically optimized for enum keys and is more memory-efficient than a HashMap
.EnumMap
uses an array internally to store the values, which makes it more memory-efficient than using a generic map when working with enum constants.EnumMap
iterates over keys in the natural order of the enum constants, the order is predictable and follows the declaration of the enum.You should consider using EnumMap
in the following cases:
EnumMap
provides a better, more efficient alternative to using a generic map like HashMap
or TreeMap
.EnumMap
is more memory-efficient.EnumMap
provides better performance than traditional HashMap
.