Register Login

Difference between Comparable and Comparator

Updated Sep 11, 2019

In Java, you can write your own programs if you want to sort a list of items. You might have a collection class such as ArrayList or HashSet. In this case, if you want to sort the objects stored in the classes, it might be difficult by writing complex programs.

To help you sort the elements of a collection, Java provides two interfaces. They are Comparable and Comparator. The Comparable interface will provide you with a single technique for sorting the elements. On the other hand, the Comparator interface offers you different ways of sorting elements.

In this article, we will discuss the applications and differences between the two interfaces.

What is Comparable in Java?

Before sorting some elements, they have to be compared individually. So, for a class to compare its data members, it has to implement the java.lang.Comparable interface. The comparable object is able to compare another object with itself.

The Comparable interface is commonly used to sort the order of elements in classes defined by the user. You can use this interface to sort the following objects:

  • Objects of a Wrapper class
  • String objects
  • Objects of a user-defined class

By default, the String and Wrapper class implement the Comparable interface. Therefore, if you store a String or Wrapper class object in a set, map or a list, they will be comparable.

For example, we have a class that contains information about books. The data members are the name, author, release year and rating. For this, the Comparable interface has a method called compareTo(T obj). This will be used by sorting methods to get the desired result.

In this case, you have to override the compareTo() method in a way that it returns:

  • Negative integer if one object is less than the other
  • Positive integer if one object is greater than the other
  • Zero if they are equal

But when you make an element in a collection comparable, you will get only one opportunity to implement the compareTo() method. So, you can sort the elements by a single criterion, such as Author of the book.

Example:

//Java Program Example for Comparable

import java.io.*;
import java.util.*;

class Customer implements Comparable<Customer>{

  //Variable Declaration
  private String name;
  private int age;
  private int bill;

  //Function to compare values start

  public int compareTo(Customer m){
    return this.age - m.age;
  }
  //function ends

  //Customer Constructor

  public Customer (String nm, int ag, int bl)
  {
    this.name = nm;
    this.age = ag;
    this.bill = bl;
  }

  public String getName() { return name; } //Returns the name of customer
  public int getAge() { return age; } //Returns the age of customer
  public int getBill() {return bill; } //Returns the bill of customer

}

// Main / Driver Class of program
class Main
{
  public static void main (String[] args) {
    //object declartion for list
    ArrayList<Customer> list = new ArrayList<Customer>();

    //Adding Values to the list
    list.add(new Customer("Customer 1",39, 49));
    list.add(new Customer("Customer 2",14, 275));
    list.add(new Customer("Customer 3",75, 12));
    list.add(new Customer("Customer 4",25, 99));
    list.add(new Customer("Customer 5",23, 5));

    //Here it will call the CompareTo function
    Collections.sort(list);

    System.out.println("Customers after sorting on Age : ");

    for(Customer Customer: list)
    {
      System.out.println(Customer.getName() + " " +
                            Customer.getAge() + " " +
                            Customer.getBill());
    }
  }
}


OUTPUT :

Customers after sorting on Age :
Customer 2 14 275
Customer 5 23 5
Customer 4 25 99
Customer 1 39 49
Customer 3 75 12

What is Comparator in Java?

The objects within a user-defined class can be sorted using the Comparator interface. The major between this interface and Comparable is that Comparator provides you with the functionality of comparing multiple data members.

The java.util package contains the Comparator inerface. The Comparator has two methods:

  • public int compare (Object obj1, Object obj2) – It compares the first and second object passed into it
  • public boolean equals (Object element) – This method compares the current object with the other object that is specified in the method

When you use the compare method, it should return the following:

  • You will get back a negative integer if the other argument is greater than the first argument
  • A positive integer, if the first argument passed is greater than the second argument
  • If both arguments are equal, you get a zero

In the case of the equals method, checks whether the invoking comparator and object are equal. Here, the obj argument is used for testing equality. If both the obj argument and the invoking objects are Comparator objects, the method will return true. The ordering of the objects has to be same. Or else the method will return a false value.

You can use the Comparator interface in the following cases:

  • For sorting a list of objects or an array using a custom order
  • You can sort the same list of objects or array on different fields
  • For sorting a list of objects or an array whose source code cannot be altered to implement the Comparable interface
  • The Comparator interface is useful while using a Group by sorting a list of objects or an array for different fields

The Collections class has a sort method to organise elements of a Comparator type and a list. You can sort the list elements having Comparator type by the Collections.sort(List, Comparator).

Example:

//Java program for Comparator

import java.io.*;
import java.util.*;

// Class 'Customer' implements Comparable

class Customer implements Comparable<Customer>{

  //Variable Declaration

  private String name;
  private int age;
  private int bill;

  //Function to compare values start

  public int compareTo(Customer m){
    return this.age - m.age;
  }

  //function ends

  //Customer Constructor

  public Customer (String nm, int ag, int bl)
  {
    this.name = nm;
    this.age = ag;
    this.bill = bl;
  }

  public String getName() { return name; }  //Returns the name of customer
  public int getAge() { return age; }  //Returns the age of customer
  public int getBill() {return bill; }  //Returns the bill of customer

}

//This class used to get sorting on Name
class NameCompare implements Comparator<Customer>
{
    public int compare(Customer c1, Customer c2)
    {
        return c1.getName().compareTo(c2.getName());
    }
}

//Main / Driver Class of program

class Main
{
  public static void main (String[] args) {

    //object declartion for list

    ArrayList<Customer> list = new ArrayList<Customer>();

    //Adding Values to the list

    list.add(new Customer("Customer 1",39, 49));
    list.add(new Customer("Customer 2",14, 275));
    list.add(new Customer("Customer 3",75, 12));
    list.add(new Customer("Customer 4",25, 99));
    list.add(new Customer("Customer 5",23, 5));

    //Here it will call the CompareTo function

    Collections.sort(list);

    //Sorting on Age

    System.out.println("Customers after sorting on Age : ");

    for(Customer Customer: list)
    {
      System.out.println(Customer.getName() + " " +
                            Customer.getAge() + " " +
                            Customer.getBill());
    }

    //Sorting on Name

    System.out.println("\nCustomer Sorted by name : ");
        NameCompare nameCompare = new NameCompare();
        Collections.sort(list, nameCompare);
        for (Customer Customer: list)
            System.out.println(Customer.getName() + " " +
                            Customer.getAge() + " " +
                            Customer.getBill());
  }
}

OUTPUT :

Customers after sorting on Age :
Customer 2 14 275
Customer 5 23 5
Customer 4 25 99
Customer 1 39 49
Customer 3 75 12

Customer Sorted by name :
Customer 1 39 49
Customer 2 14 275
Customer 3 75 12
Customer 4 25 99
Customer 5 23 5 

Comparator vs Comparable

Basis of Comparison

Comparable

Comparator

Number of sorting techniques

It offers you with a single sorting technique. For example, you are able to sort the elements based on single property like ID or name.

This interface gives you multiple techniques for sorting elements.  

Ordering

It is useful for objects that have a natural ordering. For example, serial number of employees.

It is useful for objects that may not have a natural ordering.

Package

The interface is present in the java.lang package

This is present in the java.util package

Methods

This interface has the public int compareTo() for sorting elements

This interface has the public int compare() and boolean equals() method

Comparison procedure

In the compareTo(Object obj), the object that invokes the method is compared to the object passed in the method

Here, in the compare(Object obj1, Object obj2) method, both objects are compared that are passed to this method  

Effect on the original class

Here the original class is affected and it is modified. This is because the interface is implemented by the class whose objects you want to compare

This interface does not modify the original class. Here, the interface is implemented by a separate class instead of the original one.

List elements

The Collection class provides you with a Collections.sort(List) to compare list elements of Comparable type

The Collection class provides you with Collections.sort(List, Comparator) to sort list elements that have Comparator type

Conclusion

The Comparable and Comparator interfaces have slightly different applications. You have to use them based on your requirements. The Comparable interface is used when you want to sort a collection of elements based on a single element. On the other hand, you can use the Comparator interface to sort elements based on more than one criterion.

For the Comparable method, the Collection.sort() and Arrays.sort() use the compareTo() method. But in case of the Comparator interface, you can use the compare() method by providing the Comparator class.

If you want to sort the elements based on their natural sorting order, you have to use Comparable. For sorting elements according to a custom sorting order, use the Comparator.


×