2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-06-07 17:16:40 +02:00
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.
2021-04-28 16:49:39 +02:00
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2023-06-07 17:16:40 +02:00
[source,java,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
2023-06-07 17:16:40 +02:00
public enum Color {
RED, GREEN, BLUE, ORANGE;
2021-04-28 16:49:39 +02:00
}
2023-06-07 17:16:40 +02:00
Map<Color, String> colorMap = new HashMap<>(); // Noncompliant
2021-04-28 16:49:39 +02:00
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2023-06-07 17:16:40 +02:00
[source,java,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
2023-06-07 17:16:40 +02:00
public enum Color {
RED, GREEN, BLUE, ORANGE;
2021-04-28 16:49:39 +02:00
}
2023-06-07 17:16:40 +02:00
Map<Color, String> colorMap = new EnumMap<>(Color.class); // Compliant
2021-04-28 16:49:39 +02:00
----
2021-04-28 18:08:03 +02:00
2023-06-07 17:16:40 +02:00
== Resources
* https://www.baeldung.com/java-enum-map[A Guide to EnumMap - Baeldung]
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Convert this Map to an EnumMap.
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]