Consider implementing comparable of a class in Java

Special notes

  • By implementing comparable a class indicates that its instance has a natural ordering
  • equals() method imposes a global equivalence on all objects but compareTo() method does not have to work for all types of object
  • If hasCode contract is violated then other classes those depend on hashing will break. Similarly, if compareTo() contract is violated then it will break classes that depend on sorting.
  • The equality test imposed by a compareTo method must obey the same restrictions imposed by the equals contract: reflexivity, symmetry, and transitivity.
  • If a class has multiple significant fields we must start with the most significant field and work the way down.
  • Using relational operator < and > is no longer recommended and it can issue errors
  • In java 8 the compareTo method can be implemented with comparators
  • Use static compare() method in the boxed primitive classes
  • Use the comparator construction method in the Comparator interface

When to use Comparable and Comparator?

Use Comparable if you want to define a default (natural) ordering behaviour of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this.

Use Comparator if you want to define an external controllable ordering behavior, this can override the default ordering behavior.

Example of Comparable

Please check the following code:

class User implements Comparable{
    String firstName;
    String lastName;

    @Override
    public int compareTo(User other){
        int last = this.lastName.compareTo(other.lastName);
        return last == 0 ? this.firstName.compareTo(other.firstName) : last;
    }
}

// Usage
public List listUsers(){
    List users = readUsersFromDB();
    Collections.sort(users);
    return users;
}
Share