A class that overrides compareTo but not equals may not implement a natural ordering that is consistent with equals.

Although this consistency is not strictly required by the compareTo contract, usually both methods should be overridden to ensure that they are consistent, that is, that x.compareTo(y)==0 is true if and only if x.equals(y) is true, for any non-null x and y.

In the following example, the class InconsistentCompareTo overrides compareTo but not equals.

In the following example, the class InconsistentCompareToFix overrides both compareTo and equals.

If you require a natural ordering that is inconsistent with equals, you should document it clearly.

  • J. Bloch, Effective Java (second edition), Item 12. Addison-Wesley, 2008.
  • Java API Specification: Comparable.compareTo, Object.equals.