1

I have recently started learning Java. I was looking at Comparable and Comparator. One of the difference I read was "when you have one sorting criteria, use comparable interface and for more than one use Comparator". But for Comparable I can use multiple sorting criteria's too like below :

class Employee implements Comparable<Employee>{
    public int empID;
    public int empStartDate;

    public int compareTo(Employee empObj){
        int result = this.empID - empObj.empID;
        if(result == 0){
            result = this.empStartDate - empObj.empStartDate;
        }
        return result;
    }
}

I do understand other differences they have. But I am kind of stuck on this difference (Single and multiple sorting criteria). Please correct me if I am wrong. Why is Comparable recommended for single sorting criteria if we can do using above approach? Could someone please explain me with an example? Thank you!

1 Answers1

3

Why is Comparable recommended for single sorting criteria if we can do using above approach?

There is no generally accepted recommendation for that.

Wherever you read that is mistaken.


Comparable vs Comparator is not at all about whether you're comparing one or many values.

An object can have (at most) one natural order. If it does, that natural order is implemented using Comparable. It is actually written in the javadoc of Comparable:

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

Whether or not the object has a natural order, (alternative) ordering can be implemented using Comparator.

Neither is about the complexity of the comparison being done.


Unrelated:

Do not calculate compare / compareTo result using integer subtraction, since it will fail if the two values are more than MAX_VALUE apart (numeric overflow).

Always use Integer.compare(x, y) when comparing int values (available since Java 7). Same for Long.compare​(x, y).

Andreas
  • 154,647
  • 11
  • 152
  • 247