Comparable and Comparator in Java – Difference Between Them

Key Difference between Comparable and Comparator in Java

  • Comparable in Java is an object to compare itself with another object, whereas Comparator is an object for comparing different objects of different classes.
  • Comparable provides the compareTo() method to sort elements in Java, whereas Comparator provides compare() method to sort elements in Java.
  • A comparable interface is present in java.lang package, whereas the Comparator interface is present in java.util package.
  • Comparable provides a single sorting sequence, while Comparator provides multiple sorting sequences.
  • Comparable affects the original class, whereas comparator doesn’t affect the original class.
Difference between Comparable and Comparator in Java
Difference between Comparator vs Comparable in Java

What is Comparable in Java?

Comparable in Java is an object to compare itself with another object. It helps to sort the list of custom objects. The java.lang.Comparable interface should be implemented by a class in order to compare its instances. Array of objects implementing a comparable interface is sorted automatically by Arrays.sort and Collections.sort methods.

What is Comparator in Java?

Comparator in Java is an object for comparing different objects of different classes. Comparator interface in Java is also used to arrange the objects of user-defined classes. It includes two important comparator interface methods known as compare (Object obj1, Object obj2) and equals (Object element).

Differences between Comparable and Comparator in Java

Here is the main difference between Java Comparable and Comparator:

Comparable Comparator
Comparable provides compareTo() method to sort elements in Java. Comparator provides compare() method to sort elements in Java.
Comparable interface is present in java.lang package. Comparator interface is present in java.util package.
The logic of sorting must be in the same class whose object you are going to sort. The logic of sorting should be in separate class to write different sorting based on different attributes of objects.
The class whose objects you want to sort must implement comparable interface. Class, whose objects you want to sort, do not need to implement a comparator interface.
It provides single sorting sequences. It provides multiple sorting sequences.
This method can sort the data according to the natural sorting order. This method sorts the data according to the customized sorting order.
It affects the original class. i.e., actual class is altered. It doesn’t affect the original class, i.e., actual class is not altered.
Implemented frequently in the API by: Calendar, Wrapper classes, Date, and
String.
It is implemented to sort instances of third-party classes.
All wrapper classes and String class implement comparable interface. The only implemented classes of Comparator are Collator and RuleBasedColator.

Method used in Comparable

The following is an important method used in the Comparable interface:

CompareTo():

CompareTo() method is used to perform natural sorting on string. The meaning of natural sorting is the sort order which applies on the object, e.g., numeric order for sorting integers, alphabetical order for String, etc.

The syntax of CompareTo() method is as follows:

int compareTo(T obj)

In the above syntax, T signifies the type of objects you are going to compare.

CompareTo() method compares the object with T obj.

Output:

  • It returns 0 if the values are equal.
  • In case, if the object has a lesser value, then this method returns a negative value.
  • If the object has a higher value, it returns a positive value.

CompareTo() Method Example:

The following program of Java comparable example shows the comparison of two characters, “a” and “b”. Character “a” comes before “b” alphabetically.

Therefore, output is -1. Character “b” comes after “a” alphabetically. Hence output is 1. Character “a” and “b” both are equivalent. Hence output is 0.

public class Sample_String {
    public static void main(String[] args) {
        String str_Sample = "a";
        System.out.println("Compare To 'a' b is : " + str_Sample.compareTo("b"));
        str_Sample = "b";
        System.out.println("Compare To 'b' a is : " + str_Sample.compareTo("a"));
        str_Sample = "b";
        System.out.println("Compare To 'b' b is : " + str_Sample.compareTo("b"));
    }
}

Output

Compare To 'a' b is : -1
Compare To 'b' a is : 1
Compare To 'b' b is : 0

Method used in Comparator

Following are the important methods used in comparator interface:

Compare():

Compare() enables you to order objects. To do this, you have to create a class that implements comparator interface. After this, you need to override it’s compare method.

The syntax of compare() method is as follows:

compare(Object obj1, Object obj2)

In the above syntax, obj1 and obj2 are two objects that you have to compare using compare() method.

Output:

  • It returns a negative integer if the first argument is less than the second one.
  • Returns zero if the first argument and second argument is equal.
  • This method can return a positive integer, in case the first argument is greater than the second.

You have to ensure that the relation is transitive. For example, ((compare(a, b)>0) && (compare(b, c)>0)) which implies compare(a, c)>0.

Compare Method Example:

In the below program of Java comparator example, there are 6 variables. “x”, “y”, “p”, “q”, “r”, and “s”. The output is -1 as the value of “x”, 20 is less than the value of “y”, 30. The output is 0 because the value of “p”, 40 is equal to the value of “q”, 40.

import java.lang.Integer; 
public class example { 
    public static void main(String args[]) 
    { 
        int x = 20; 
        int y = 30; 
        // as 10 less than 20, 
        // Output will be a value less than zero 
        System.out.println(Integer.compare(x, y)); 
        int p = 40; 
        int q = 40; 
        // as 30 equals 30, 
        // Output will be zero 
        System.out.println(Integer.compare(p, q)); 
        int r = 20; 
        int s = 7; 
        // as 15 is greater than 8, 
        // Output will be a value greater than zero 
        System.out.println(Integer.compare(r, s)); 
    } 
}

Output:

-1
0
1

Equals():

Equals() verifies whether the number object is equal to the object, which is passed as an argument or not.

The syntax of the equals() method is as follows:

public boolean equals(Object o)

This method takes two parameters 1) any object 2) return value. It returns true if the passed argument is not null and is an object of the similar type having the same numeric value.

Equals Method Example:

In the below example, we are comparing the four variables with each other. Three variables are of type integer and one of type short. The first result is false as the value of p, which is 5, is not equal to the value of q, which is 20.

The second result is true because the value of variable p and r is the same, which is 5. Lastly, the output is false, as variable p and s have different assigned values.

public class Test { 
   public static void main(String args[]) {
      Integer p = 5;
      Integer q = 20;
      Integer r =5;
      Short s = 5;
      System.out.println(p.equals(q));  
      System.out.println(p.equals(r)); 
      System.out.println(p.equals(s));
   }
}

Output

false
true
false

Best Practices While Using Comparator and Comparable in Java

  • Use a comparable interface when the comparison is standard for the specific class.
  • You can use lambdas with a comparator.
  • Many core classes available in implements a comparable interface.
  • It is possible to use TreeSet and TreeMap or while sorting Set or Map.
  • The compareTo() method works with comparator as well as comparable.
  • Use the comparator interface only when you < required more flexibility.
  • The compareTo() method will return a positive integer if the first object is greater than the other, negative if it is lower, and zero if both are the same.