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
Cis said to be consistent withequalsif and only ife1.compareTo(e2) == 0has the same boolean value ase1.equals(e2)for everye1ande2of classC. Note thatnullis not an instance of any class, ande.compareTo(null)should throw aNullPointerExceptioneven 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 theequalsmethod.For example, if one adds two keys
aandbsuch 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) becauseaandbare equivalent from the sorted set's perspective.Virtually all Java core classes that implement
Comparablehave natural orderings that are consistent withequals. One exception isjava.math.BigDecimal, whose natural ordering equatesBigDecimalobjects with equal values and different precisions (such as4.0and4.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