Appearance
EnumMap
Because HashMap
uses the hashCode()
of the key to calculate an index in the internal array, it achieves high search efficiency by trading space for time. This allows it to directly locate the value in the internal array.
If the key object is of the enum
type, we can use EnumMap
, which is provided by the Java Collections Framework. EnumMap
internally stores values in a very compact array, and it can directly locate the index in the array based on the enum
key without the need to compute the hashCode()
. This not only ensures the highest efficiency but also avoids any additional space overhead.
Let's use the DayOfWeek
enum as an example to implement a translation feature:
java
import java.time.DayOfWeek;
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<DayOfWeek, String> map = new EnumMap<>(DayOfWeek.class);
map.put(DayOfWeek.MONDAY, "Monday");
map.put(DayOfWeek.TUESDAY, "Tuesday");
map.put(DayOfWeek.WEDNESDAY, "Wednesday");
map.put(DayOfWeek.THURSDAY, "Thursday");
map.put(DayOfWeek.FRIDAY, "Friday");
map.put(DayOfWeek.SATURDAY, "Saturday");
map.put(DayOfWeek.SUNDAY, "Sunday");
System.out.println(map);
System.out.println(map.get(DayOfWeek.MONDAY));
}
}
When using EnumMap
, we typically reference it through the Map
interface. As a result, swapping between HashMap
and EnumMap
is seamless from the client's perspective.
Summary
If the key of a Map
is of the enum
type, it is recommended to use EnumMap
. This ensures both high speed and space efficiency.
When using EnumMap
, follow the principle of programming to an abstraction by holding the Map
interface.