71 lines
1.7 KiB
Plaintext
71 lines
1.7 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://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[]
|