Comparable vs Comparator in Java

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 the 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
Difference between Comparable and Comparator

Here, I have analyzed the difference between comparable and Comparator and will comprehensively evaluate their pros and cons.

What is comparable in Java?

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

Method used in Comparable

I would like to highlight an important method that I frequently use in the Comparable interface:

CompareTo():

CompareTo() method is used to perform natural sorting on a string. The meaning of natural sorting is the sort order that applies to 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.
  • If the object has a lower value, then this method returns a negative value.
  • If the object has a higher value, it returns a positive value.

An Example of Comparable in Java

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

Therefore, the output is -1. The character “b” comes after “a” alphabetically. Hence, the output is 1. Characters “a” and “b” are both equivalent. Hence, the 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

What is a comparator in Java?

A comparator in Java is an object for comparing different objects of different classes. The 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).

Method used in Comparator

In my practice, I frequently rely on the following critical methods of the comparator interface:

Compare():

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

The syntax of the 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 the compare() method. 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 are equal.
  • This method can return a positive integer in the event that 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.

An Example of Comparable in Java

In the below 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, and 2) a return value. It returns true if the passed argument is not null and is an object of a similar type having the same numeric value.

Equals Method Example:

In the below example, I will be comparing the four variables with each other. Three variables are of type integer, and one is 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 variables p and r is the same, which is 5. Lastly, the output is false, as variables 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

Differences between Comparable and Comparator in Java

I often see confusion between Java Comparable and Comparator; here’s the main difference:

 

Difference between Comparable and Comparator in Java
Difference between Comparable and Comparator in Java

 

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

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 of the core classes available implement a comparable interface.
  • It is possible to use TreeSet and TreeMap while sorting Set or Map.
  • The compareTo() method works with comparator as well as comparable.
  • Use the comparator interface only when you < require 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.

How to Choose Between a Comparable and a Comparator

Conclusively, my practical experience suggests that leveraging Comparable and Comparator in Java significantly elevates the control we have over data sorting, enhancing both performance and functionality.