If all the keys in a Map
are values from a single enum, it is recommended to use an EnumMap
as the specific
implementation. An EnumMap
, which has the advantage of knowing all possible keys in advance, is more efficient compared to other
implementations, as it can use a simple array as its underlying data structure.
Noncompliant code example
public enum Color {
RED, GREEN, BLUE, ORANGE;
}
Map<Color, String> colorMap = new HashMap<>(); // Noncompliant
Compliant solution
public enum Color {
RED, GREEN, BLUE, ORANGE;
}
Map<Color, String> colorMap = new EnumMap<>(Color.class); // Compliant