rspec/rules/S3552/java/rule.adoc

73 lines
1.6 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
The Java 8 version of ``++HashMap++`` handles key clashes by storing nodes in a binary tree when more than 11 keys clash with each other, and that tree needs to know the relative order of the keys. If you don't provide a ``++compareTo++`` method, ``++System.identityHashCode()++`` will be used as the fallback, and that typically returns a value based on the object's memory location, resulting in a performance degradation to ``++O(n)++`` where ``++n++`` is the number of objects at that map location.
Therefore, it's considered a best practice to implement ``++compareTo++`` in classes that are used as ``++HashMap++`` keys.
*Note* that this rule is automatically disabled when the project's ``++sonar.java.source++`` is lower than ``++8++``.
=== Noncompliant code example
2022-02-04 17:28:24 +01:00
[source,java]
----
public class Key {
@Override
public boolean equals(Object obj) {
/* ... */
}
@Override
public int hashCode() {
/* ... */
}
}
public void doTheThing() {
Map <Key,String> map = new HashMap<>(); // Noncompliant
// ...
}
----
=== Compliant solution
2022-02-04 17:28:24 +01:00
[source,java]
----
public class Key implements Comparable{
@Override
public boolean equals(Object obj) {
/* ... */
}
@Override
public int hashCode() {
/* ... */
}
@Override
public int compareTo(Object o) {
//...
}
}
public void doTheThing() {
Map <Key,String> map = new HashMap<>();
// ...
}
----
ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)
=== on 3 Mar 2016, 17:27:44 Ann Campbell wrote:
http://www.javaspecialists.eu/archive/Issue235.html
endif::env-github,rspecator-view[]