rspec/rules/S6411/java/rule.adoc

71 lines
1.7 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2022-04-21 13:36:28 +02:00
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
2022-04-21 13:36:28 +02:00
[source,java]
----
class MyKeyType {
// ...
}
class Program {
Map<MyKeyType, MyValueType> data = new HashMap<>(); // Noncompliant
Map<MyKeyType, MyValueType> buildMap() { // Noncompliant
//...
}
}
----
=== Compliant solution
2022-04-21 13:36:28 +02:00
[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
2022-04-21 13:36:28 +02:00
- 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[]
2022-04-21 13:36:28 +02:00
=== Implementation Specification
=== Message
The key type should implement Comparable.
=== Highlighting
Variable type, method return type and expressions.
2022-04-21 13:36:28 +02:00
endif::env-github,rspecator-view[]