When you implement the Comparator interface in Java, is it required to rewrite the equals method? The java compiler does not complain if I do not do that. But is that OK to do?
When you implement the Comparator interface in Java, is it required to rewrite the
Share
The
Comparator<SomeClass>interface is implemented as a separate class to theSomeClassclass. There is no need forSomeClass.equals(Object)to be consistent with the comparator. (Indeed, it would pretty much defeat the purpose of having a separate comparator object!)On the other hand, if
SomeClassimplementsComparable<SomeClass>it is strongly recommended thatequals(Object)andcompare(SomeClass, SomeClass)to be consistent. The javadoc forComparablesays this:The Java compiler cannot determine whether
equalsandcompareare consistent. (Orequalsandhashcodefor that matter.) It is theoretically impossible to do this in all cases, and beyond the "state of the art" in practice. And a simple test that you’ve overriddenequalswould give false warnings in some cases.You can’t rely on the compiler to point out logic errors in your application.
If the question is actually about the semantics of
Comparable<T>.equals(Object), then the answer is in the javadocs:Ted Hopp commented thus:
First, Ted is misconstruing what I wrote. I said:
Second, it is neither a good idea or a bad idea for comparators to be consistent with equals. It entirely depends on the intended semantics of equals, and the intended purpose of the comparator.
If the comparator is used for ordering elements in a TreeSet, then inconsistency with
equalsis going to result in strange behavior.If the comparator is used for ordering a list of objects for display purposes, then consistency with
equalsis likely to be irrelevant.