In the previous article, we see how we can define equality in our class and compare two objects using the equals() method. In this article, we are going to define additional less than and greater than relations in our class using the Comparable<T> interface.

The Comparable<T> interface defines relative order in our class, which is useful for sorting. For example, let’s say we’re working on a program that keeps a list of books in sorted order by book title. In order to keep the list sorted, we need to know more than just if two books are equal. What we need is which book should come before the other.

Comparable Interface

The goals of Comparable is to compare two objects and see if one is less than, greater than, or equal to the other. The interface only has 1 method, compareTo(), which takes an object as parameter. For objects a and b that implements Comprable, a.compareTo(b) returns:

  1. Negative integer: if a < b
  2. Positive integer: if a > b
  3. 0: if a = b

Note, a < b means a is logically less than b, depends on how compareTo() is implemented.

Example

The following snippet shows an example Person class that defines the ordering based only on the person’s age.

class Person implements Comparable<Person> {
    private String Name;
    private String Gender;
    private int    age;

    /** This method is required by Comparable interface */
    public compareTo(Person that) {
        if(this.age == that.age) return 0;
        else if(this.age < that.age)  return -1;
        else return 1;
    }
}

The following code creates an array of 3 Person objects and sorts the array using Java’s sorting method.

class Demo {
    public static void main(String[] args)
    {
        Person[] a = new Person[3]; //Create an array of Person
        a[0] = new Person("John", "M", 40); //Create Person Objects
        a[1] = new Person("Anne", "F", 20);
        a[2] = new Person("Bill", "M", 50);
        Arrays.sort(a); //Sort the array

        //After the sort, a becomes
        //a[0] = {"Anne", "F", 20}
        //a[1] = {"John", "M", 40}
        //a[2] = {"Bill", "M", 50}
    }
}

When to Implement

When should the Comparable interface be used? It makes sense for a numeric data type to implement this interface since, numeric values usually have a natural ordering. More generally, whenever your class has an natural ordering, it is a good idea to implement this interface, so that objects of your classes can be sorted by Java’s sorting algorithms.

Comparable is also implemented by many of build-in types and wrapper classes, so that they can be sorted in collections. A few examples of these classes include: Integer, Double, and String.