📜  Java EnumMap(1)

📅  最后修改于: 2023-12-03 14:42:13.962000             🧑  作者: Mango

Java EnumMap

Java EnumMap is a special map implementation in Java that is optimized for storing key-value pairs of enum types. It is a part of the Java Collections framework and was introduced in Java 5.

EnumMap Basics

An EnumMap is a high-performance specialized Map implementation that associates keys with values. However, unlike a typical Map, it can only be used with keys that are enums. One of the primary benefits of using EnumMap is its speed, which makes it an ideal choice when dealing with a small set of keys (enums).

Here is an example of how to create an empty EnumMap:

// Creating an empty EnumMap.
EnumMap<WeekDays, String> enumMap = new EnumMap<>(WeekDays.class);

In the above example, WeekDays is an enum type that will be used as keys in the new EnumMap.

EnumMap Operations

An EnumMap supports all the basic Map operations. These include:

  • Inserting and Retrieving Key-Value Pairs
// Insert a key-value pair.
enumMap.put(WeekDays.MONDAY, "Monday");

// Retrieve the value for a given key.
String value = enumMap.get(WeekDays.MONDAY);
  • Removing Key-Value Pairs
// Remove a key-value pair.
enumMap.remove(WeekDays.MONDAY);
  • Clearing the Map
// Clearing the map.
enumMap.clear();
  • Checking if the Map contains a Key
// Checking if the map contains a key.
boolean containsKey = enumMap.containsKey(WeekDays.MONDAY);
  • Checking if the Map contains a Value
// Checking if the map contains a value.
boolean containsValue = enumMap.containsValue("Monday");
  • Getting the Size of the Map
// Getting the size of the map.
int size = enumMap.size();
  • Iterating through the Map
// Iterating through the map.
for (Map.Entry<WeekDays, String> entry : enumMap.entrySet()) {
    WeekDays key = entry.getKey();
    String value = entry.getValue();

    // Perform some operation with the key-value pair.
}
Conclusion

In conclusion, Java EnumMap is a specialized map implementation that is designed to work with enum keys. It offers high performance and optimized performance with a small set of keys. It supports all the basic Map operations and can be used in a variety of scenarios where enum keys are required. Therefore, it is an essential tool for any Java developer working with enums.