Search code examples
javacomparable

Java Comparable object equals() and compareTo() returning different results


In this example I have an Employee class that implements Comparable, and below is the code for compareTo()

@Override
public int compareTo(Employee e) {
    if (getName().equals(e.getName())) return 0;
    else if (getPay() < e.getPay()) return -1;
    else return 1;
}

When I do employee1.equals(employee2); , given that employee1 and 2 have the same name, I am expecting the result to be true but it returns false.

But when I did employee1.compareTo(employee2); I get the expected result, which is 0.

Please help me understand the nature of Comparable. Thanks!


Solution

  • compareTo and equals methods are completely unrelated from the perspective of the JVM. It is programmer's duty to make natural order consistent with equals.

    If only compareTo method is provided for the class Employee, the default implementations, derived from Object is inherited. You should override equals method (together with hasCode) to get consistent results.