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

----
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

----
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)

include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]
