Can somebody put some light on what are the Consequences when compareTo()
is inconsistent with equals()
of a class. I have read that if Obj1.compareTo(Obj2) = 0
then it's not mandatory to be Obj1.equals(Obj2) = true
. But what is the consequence if this happens. Thanks.
But if compareTo() is "inconsistent with equals" then this code can throw the exception, because a. compareTo(b) can return zero when a. equals(b) is false.
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. Not all objects can be logically ordered, so a compareTo() method doesn't always make sense.
Java String compareTo() Method The method returns 0 if the string is equal to the other string. A value less than 0 is returned if the string is less than the other string (less characters) and a value greater than 0 if the string is greater than the other string (more characters).
Now, if Comparable returns Zero, it means two objects are the same by comparison. If two objects are the same by using the equals method, it returns true.
The documentation for Comparable
explains this in some detail:
The natural ordering for a class
C
is said to be consistent withequals
if and only ife1.compareTo(e2) == 0
has the same boolean value ase1.equals(e2)
for everye1
ande2
of classC
. Note thatnull
is not an instance of any class, ande.compareTo(null)
should throw aNullPointerException
even thoughe.equals(null)
returnsfalse
.It is strongly recommended (though not required) that natural orderings be consistent with
equals
. This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely" when they are used with elements (or keys) whose natural ordering is inconsistent withequals
. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of theequals
method.For example, if one adds two keys
a
andb
such that(!a.equals(b) && a.compareTo(b) == 0)
to a sorted set that does not use an explicit comparator, the second add operation returnsfalse
(and the size of the sorted set does not increase) becausea
andb
are equivalent from the sorted set's perspective.Virtually all Java core classes that implement
Comparable
have natural orderings that are consistent withequals
. One exception isjava.math.BigDecimal
, whose natural ordering equatesBigDecimal
objects with equal values and different precisions (such as4.0
and4.00
).
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