Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 315
aps Avatar asked Aug 07 '11 05:08

aps


People also ask

What is Java Lang comparable?

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.

What is difference between == equals () and compareTo () method in Java?

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.

Why compareTo () should be consistent to equals () method in Java?

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.

What is comparable in Java with example?

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.


2 Answers

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.

like image 95
dlev Avatar answered Sep 30 '22 22:09

dlev


From Javadoc of java.lang.Comparable:

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

like image 33
Andrey Adamovich Avatar answered Sep 30 '22 23:09

Andrey Adamovich