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()
?
From Javadoc of java.lang.Comparable:
While it is recommended, it is not required that
.equals()
and.compareTo()
have the same behaviour.Just look at the BigDecimal API: http://download.oracle.com/javase/1,5.0/docs/api/java/math/BigDecimal.html#equals(java.lang.Object)
If you do this, and you put those objects into a sorted set, the set will misbehave. From the docs on SortedSet:
For example, a TreeSet may (erroneously) contain two objects where
even though
While it is recommended (and pretty sensible) that having
a.compareTo(b) == 0
imply thata.equals(b)
(and visa versa), it is not required.Comparable
is intended to be used when performing an ordering on a series of objects, whereasequals()
just tests for straight equality.This link has some good information on implementing
compareTo
properly.