2

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!

Chan Jing Hong
  • 2,251
  • 4
  • 22
  • 41

3 Answers3

3

The point of Comparable is to answer the question "If I were to put these things (in this case, Employees) in order, how would I know whether one should be in front of or behind the other? This means that it is essential that the fields you are checking in compareTo are exactly the same as those you are checking in equals. This helps to make these two consistent.

It is also important that your compareTo method is consistent with itself - in other words, Math.signum(a.compareTo(b)) = -Math.signum(b.compareTo(a)). In your case, two employees with different names and the same pay would always return 1, which means that both of these employees are supposed to come after each other when sorted (which doesn't make sense).

Joe C
  • 15,324
  • 8
  • 38
  • 50
1

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.

kgeorgiy
  • 1,477
  • 7
  • 9
1

You need to provide implementation for equals method (that will compare names) in Employee otherwise Java uses references equality check, thus two objects with the same name are not equal.

win_wave
  • 1,498
  • 11
  • 9