
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
72 lines
1.8 KiB
Plaintext
72 lines
1.8 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Maps use hashes of the keys to select a bucket to store data in.
|
|
Objects that hash to the same value will be added to the same bucket.
|
|
|
|
When the hashing function has a poor distribution, buckets can grow to very large sizes.
|
|
This may negatively affect lookup performance, as, by default, matching a key within a bucket has linear complexity.
|
|
|
|
In addition, as the default hashCode function can be selected at runtime, performance expectations cannot be maintained.
|
|
|
|
Implementing Comparable mitigates the performance issue for objects that hash to the same value.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
class MyKeyType {
|
|
// ...
|
|
}
|
|
|
|
class Program {
|
|
Map<MyKeyType, MyValueType> data = new HashMap<>(); // Noncompliant
|
|
|
|
Map<MyKeyType, MyValueType> buildMap() { // Noncompliant
|
|
//...
|
|
}
|
|
}
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
class MyKeyType implements Comparable<MyKeyType> {
|
|
// ...
|
|
}
|
|
|
|
class MyChildKeyType extends MyKeyType {
|
|
// ...
|
|
}
|
|
|
|
class Program {
|
|
Map<MyKeyType, MyValueType> data = new HashMap<>();
|
|
Map<MyChildKeyType, MyValueType> data = new HashMap<>();
|
|
|
|
Map<MyKeyType, MyValueType> buildMap() {
|
|
//...
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
- https://www.kb.cert.org/vuls/id/903934
|
|
- https://dzone.com/articles/java-8-hashmaps-keys-and-the-comparable-interface
|
|
- https://github.com/openjdk/jdk/blob/4927ee426aedbeea0f4119bac0a342c6d3576762/src/hotspot/share/runtime/synchronizer.cpp#L760-L798
|
|
- https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Comparable.html
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
=== Implementation Specification
|
|
|
|
=== Message
|
|
The key type should implement Comparable.
|
|
|
|
|
|
=== Highlighting
|
|
|
|
Variable type, method return type and expressions.
|
|
|
|
endif::env-github,rspecator-view[]
|