java.lang.Comparable and equals

18,661

Solution 1

While it is recommended (and pretty sensible) that having a.compareTo(b) == 0 imply that a.equals(b) (and visa versa), it is not required. Comparable is intended to be used when performing an ordering on a series of objects, whereas equals() just tests for straight equality.

This link has some good information on implementing compareTo properly.

Solution 2

From Javadoc of java.lang.Comparable:

It is strongly recommended (though not required) that natural orderings be consistent with equals.

Solution 3

While it is recommended, it is not required that .equals() and .compareTo() have the same behaviour.

Just look at the BigDecimal Docs for equals() method:

Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

BigDecimal is a core class of java that has different behaviour for equals() and compareTo() and serves as a good example of the difference between 2 objects that are comparable vs truly equal.

Solution 4

Let's say the way I term two objects as equal within the equals() method is different from the way I term two objects of the same class as equal within the toCompare() of the Comparable?

If you do this, and you put those objects into a sorted set, the set will misbehave. From the docs on SortedSet:

Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface.

For example, a TreeSet may (erroneously) contain two objects where

a.compareTo(b) != 0

even though

a.equals(b) == true
Share:
18,661
aps
Author by

aps

Updated on June 18, 2022

Comments

  • aps
    aps almost 2 years

    If I implement java.lang.Comparable for a class, do I still have to override the equals() method? Or will the Comparable work for equals as well?

    If the answer is no, then what if some discrepancy arises? Let's say the way I term two objects as equal within the equals() method is different from the way I term two objects of the same class as equal within the compareTo() of the Comparable.

    Moreover, if I implement Comparable, do I also have to override equals()?