Java

How do You write Comparable in Java?

Examples of Java lists are; Vector, Stack, AttributeList, ArrayList, and LinkedList. The Java Collections class has overloaded methods to sort a list of predefined objects. The Java Arrays class has overloaded methods to sort an array of predefined objects.

The predefined sort() methods are to sort predefined objects. What about user-defined objects? Java has an interface called Comparable. An interface is a kind of class whose methods are declarations without definitions (bodies). So, a class must be implemented from an interface for the methods to be defined (given bodies). From the implemented class, objects can be instantiated from a name given by the programmer.

Java has a predefined Comparable class. The sort() methods in Collections and Arrays use the predefined comparable class to sort predefined objects. However, in order to sort a list or array of user-defined objects, the programmer has to implement (define) a user Comparable class from the Comparable interface. This user implemented (defined) class enables the sorting of user-defined objects in a list or array. So, a predefined Comparable class enables sorting of predefined objects, while a user-defined Comparable class enables sorting of user-defined objects. User-defined objects are not literals, so a class of user-defined objects needs its own user-defined Comparable implementation.

This article illustrates how to write Comparable in Java.

Example of User Defined Class

The user-defined class actually implements the Comparable interface. The Comparable interface has only one method, which is,

    int compareTo(T o)

It is either defined (given a body) to sort ascending or defined to sort descending. It returns a negative integer, or zero, or a positive integer, as its object is less than, equal to, or greater than the specified object.

This class of interest, implemented from the Comparable interface, is the user-defined class with now a defined compareTo() method. This is not a complete user-defined class, though. It can have other methods and properties (fields) of its own, depending sorely on the programmer. The objects instantiated from this user implemented class will be the objects of the list or array to be sorted. Each object has the same compareTo() method in the sorting, which controls the sorting.

Example Class

The following code shows a user-defined class for employees, from which objects (employees) will be instantiated. In order for the objects to be sorted, the class Employee implements Comparable interface and defines (gives a body) the compareTo() method as a special method of the class.

    class Employee implements Comparable<Employee> {        
        String fName; int age;    
        Employee(String fName, int age) {      
            this.fName = fName;    
            this.age = age;    
        }    
         
        public int compareTo(Employee emp) {    
            if(age < emp.age)    
                return -1;    
            else if(age == emp.age)    
                return 0;    
            else    
                return +1;
        }    
    }

There is no real object literal here. The intention is to have to sort the employees by age, ascending. This is also comparing the employee by age. And so the compareTo() has to be defined. This definition is for sorting ascending. In this method, body (definition), age and emp.age , refer to two different elements in the list or array. age refers to the element before emp.age .

A suitable main() method for this is:

        public static void main(String[] args) {
            ArrayList<Employee> al = new ArrayList<Employee>();
            al.add(new Employee("John", 40)); al.add(new Employee("Peter", 50));
            al.add(new Employee("Christopher", 30));
            Collections.sort(al);
            for (int i=0; i<al.size(); i++)
                System.out.println(al.get(i).fName + ' ' + al.get(i).age);
        }

Read through the code. The output is:

    Christopher 30
    John 40
    Peter 50

sorted ascending, by age.

Sorting Descending

The above compareTo() method definition, is for ascending. To make it sort descending, code it as follows:

        public int compareTo(Employee emp) {    
            if(age < emp.age)    
                return +1;    
            else if(age == emp.age)    
                return 0;    
            else    
                return -1;
        }

Note that < has not been changed. However, -1 returned has been changed to +1; and +1 returned has been changed to -1. With this, the output for the above specific list is:

    Peter 50
    John 40
    Christopher 30

sorted descending, by age.

Comparable for Array

A Comparable class for an array is the same as a Comparable class for a list, as explained above. The class is a programmer implemented a class that implements the Comparable interface. This programmer implemented class also defines the compareTo() method, either ascending or descending. The objects instantiated from this class become the objects for the array. The defined compareTo() method controls their sorting.

The following main method, sorts an array of the same above employees, ascending:

            Employee[] arr = new Employee[3];
            arr[0] = new Employee("John", 40); arr[1] = new Employee("Peter", 50);
            arr[2] = new Employee("Christopher", 30);
            Arrays.sort(arr);
            for (int i=0; i<arr.length; i++)
                System.out.println(arr[i].fName + ' ' + arr[i].age);
        }

Note that instead of,

        Collections.sort(al);

there is,

        Arrays.sort(arr);

this time, because an array is not really a list. The output should be

    Christopher 30
    John 40
    Peter 50

ascending, by age. This is on the condition that the body of the compareTo() method is:

        public int compareTo(Employee emp) {    
            if(age < emp.age)    
                return -1;    
            else if(age == emp.age)    
                return 0;    
            else    
                return +1;
        }

If the body was,

        public int compareTo(Employee emp) {    
            if(age < emp.age)    
                return +1;    
            else if(age == emp.age)    
                return 0;    
            else    
                return -1;
        }

then the array would be sorted descending to result in the output:

    Peter 50
    John 40
    Christopher 30

Conclusion

The predefined Comparable class enables the sorting of predefined objects, while the user-defined Comparable class enables the sorting of user-defined objects. User-defined objects are not literals, so a class of user-defined objects needs its own user-defined Comparable implementation.

The class of interest, whose objects are to be instantiated, has to implement the Comparable interface. The comparable interface has the method compareTo(), which has to be defined in the class for ascending or descending (reverse) sorting. It is this method that controls the sorting in the list or array.

The same Comparable class for sorting a list can be used for sorting an array. The class is a programmer implemented a class that implements the Comparable interface. This programmer implemented class also defines the compareTo() method, either ascending or descending. The objects instantiated from this class become the objects of the array.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.