
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.
73 lines
1.6 KiB
Plaintext
73 lines
1.6 KiB
Plaintext
== 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
|
|
|
|
[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
|
|
|
|
[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[]
|