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()
?
The Java Comparable interface, java. lang. Comparable , represents an object which can be compared to other objects. For instance, numbers can be compared, strings can be compared using alphabetical comparison etc. Several of the built-in classes in Java implements the Java Comparable interface.
equals() checks if two objects are the same or not and returns a boolean. compareTo() (from interface Comparable) returns an integer. It checks which of the two objects is "less than", "equal to" or "greater than" the other.
2) CompareTo must be in consistent with equals method e.g. if two objects are equal via equals() , there compareTo() must return zero otherwise if those objects are stored in SortedSet or SortedMap they will not behave properly.
The Comparable interface is used to compare an object of the same class with an instance of that class, it provides ordering of data for objects of the user-defined class. The class has to implement the java. lang.
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.
From Javadoc of java.lang.Comparable:
It is strongly recommended (though not required) that natural orderings be consistent with equals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With