2023-05-25 14:18:12 +02:00
|
|
|
== Why is this an issue?
|
|
|
|
|
|
|
|
According to the Java ``++Comparable.compareTo(T o)++`` documentation:
|
|
|
|
|
|
|
|
|
|
|
|
____
|
|
|
|
It is strongly recommended, but not strictly required that ``++(x.compareTo(y)==0) == (x.equals(y))++``.
|
|
|
|
|
|
|
|
Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact.
|
|
|
|
|
|
|
|
The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."
|
|
|
|
|
|
|
|
____
|
|
|
|
|
|
|
|
If this rule is violated, weird and unpredictable failures can occur.
|
|
|
|
|
|
|
|
For example, in Java 5 the ``++PriorityQueue.remove()++`` method relied on ``++compareTo()++``, but since Java 6 it has relied on ``++equals()++``.
|
|
|
|
|
|
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
|
|
|
|
[source,java]
|
|
|
|
----
|
|
|
|
public class Foo implements Comparable<Foo> {
|
|
|
|
@Override
|
|
|
|
public int compareTo(Foo foo) { /* ... */ } // Noncompliant as the equals(Object obj) method is not overridden
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
|
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
|
|
|
|
[source,java]
|
|
|
|
----
|
|
|
|
public class Foo implements Comparable<Foo> {
|
|
|
|
@Override
|
|
|
|
public int compareTo(Foo foo) { /* ... */ } // Compliant
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public boolean equals(Object obj) { /* ... */ }
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
2021-06-02 20:44:38 +02:00
|
|
|
|
2021-06-03 09:05:38 +02:00
|
|
|
ifdef::env-github,rspecator-view[]
|
2021-09-20 15:38:42 +02:00
|
|
|
|
|
|
|
'''
|
|
|
|
== Implementation Specification
|
|
|
|
(visible only on this page)
|
|
|
|
|
2023-05-25 14:18:12 +02:00
|
|
|
=== Message
|
|
|
|
|
|
|
|
Override "equals(Object obj)" to comply with the contract of the "compareTo(T o)" method
|
|
|
|
|
2021-09-20 15:38:42 +02:00
|
|
|
|
2021-06-08 15:52:13 +02:00
|
|
|
'''
|
2021-06-02 20:44:38 +02:00
|
|
|
== Comments And Links
|
|
|
|
(visible only on this page)
|
|
|
|
|
|
|
|
include::../comments-and-links.adoc[]
|
2023-06-22 10:38:01 +02:00
|
|
|
|
2021-06-03 09:05:38 +02:00
|
|
|
endif::env-github,rspecator-view[]
|