rspec/rules/S1640/java/rule.adoc

45 lines
1.0 KiB
Plaintext

== Why is this an issue?
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
[source,java,diff-id=1,diff-type=noncompliant]
----
public enum Color {
RED, GREEN, BLUE, ORANGE;
}
Map<Color, String> colorMap = new HashMap<>(); // Noncompliant
----
=== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
public enum Color {
RED, GREEN, BLUE, ORANGE;
}
Map<Color, String> colorMap = new EnumMap<>(Color.class); // Compliant
----
== Resources
* https://www.baeldung.com/java-enum-map[A Guide to EnumMap - Baeldung]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Convert this Map to an EnumMap.
endif::env-github,rspecator-view[]