Skip to content
Advertisement

java.lang.Comparable and equals

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement