Interview Question
Country: India
what if the class overrides equals and has some definition of equals() and at the same time implements comparable and compareTo() method gives some other implementation?
i.e obj.comapreTo(obj2) == 0 and obj.equals(obj2) is false?
There would still not be any problem. What you are talking about is a logical error in the program.
When you override compareTo(), you are specifying the relative ordering of elements in a collection. When you sort the elements in the collection, it's the compareTo() definition which is looked up to determine the relative order of elements. How you override equals() doesn't have any effect on the way elements get sorted.
On the other hand, if you override equals() and fail to override hashCode(), all HashMap based collections which store this object would not behave correctly. For example, if you fail to override hashCode(), 2 logically equal objects would have different hash codes and would map to 2 different keys in the HashMap instead of referring to just 1 key.
There really is no contract between compareTo() and equals().
- Prashant May 09, 2012The recommended practice is that the hashCode() method should always be overridden, if the equals() method is overridden. May be, this question was aimed at confusing the interviewee.