This tutorial explains the concept of Comparable And Comparator Interfaces In Java with examples. You will also learn about the differences between the two:
We learned all about interfaces in our earlier tutorials. An interface is used to declare abstract methods and static or final variables. By default, interface methods are public. Since Java 8, interfaces can also have static and default methods defined in them.
Java provides various built-in interfaces that we can use to perform various operations. In this tutorial, we will discuss two such interfaces i.e. Comparable and Comparator. A comparable interface is used for sorting object according to the natural ordering. Comparator interface is used to sort individual attributes of various objects.
=> Explore The Simple Java Training Series Here.
Let’s begin with a Comparable interface.
Table of Contents:
Comparable Interface In Java
Comparable interface sorts the list structures like Arrays and ArrayLists containing custom objects. Once the list objects implement Comparable interface, we can then use the Collections.sort () method or Arrays.sort () in case of the arrays to sort the contents.
But when we have custom classes and we need to sort their objects, then we will have to implement the Comparable interface in this class. The Comparable interface is a part of the java.lang package. This interface has only one method, CompareTo (). Using a comparable interface, we can sort a single data member at a time.
For example, if we have name and age as fields in our class then at a time we can either sort the class objects on name or age. We cannot sort simultaneously on both name and age.
As explained above, we can implement the Comparable interface in Java by having a custom class to implement the Comparable interface. The Comparable interface has only one method ‘compareTo’ which has to be overridden in the class to sort the custom objects.
‘CompareTo’ Method
The method ‘compareTo’ of the Comparable interface is used to compare the current object to the given object. The general syntax of the compareTo object is given below.
public int compareTo(Object obj)
As shown above, the compareTo method accepts an object as an argument (it can be any custom object) and compares it with the current object used to invoke this method.
The compareTo method returns an integer value that can have one of the following values:
- Positive (> 0) integer=> the current object > the object parameter passed.
- Negative (< 0) integer => the current object < the specified object.
- Zero (= 0) => the current object and specified object are both equal.
We can use the compareTo () method to sort:
- String type objects
- Wrapper class objects
- User-defined or custom objects
Now let’s implement an example of a Comparable interface.
Comparable Interface Example
The following Java program implements a Person class that contains name and age as member fields. This class implements a ‘Comparable’ interface that will allow us to sort the object of class Person.
Note that as we are going to sort custom objects, we need to override the ‘compareTo ()’ method of the Comparable interface.
Inside the overridden compareTo () method, we compare the age of the person object that is passed with that of the current object and accordingly return the value.
An Example Java program is given below.
//class person implementing Comparable interface class Person implements Comparable<Person> { private String name; private int age; //Person constructor public Person(String name, int age) { this.name = name; this.age = age; } //getter methods for Person members public int getAge() { return this.age; } public String getName() { return this.name; } //override toString () method @Override public String toString() { return ""; } //Override compareTo () method to compare age of two Person objects @Override public int compareTo(Person per) { if(this.age == per.age) return 0; else return this.age > per.age ? 1 : -1; } } public class Main{ public static void main(String[] args) { //declare two objects of Person class Person p1 = new Person("Adrian", 24); Person p2 = new Person("Eddie", 26); int ageDiff = p1.compareTo(p2); //compare ages of two persons declared switch(ageDiff) { case -1: { System.out.println(p2.getName() + " is older than " + p1.getName()); break; } case 1: { System.out.println(p1.getName() + " is older than " + p2.getName()); break; } default: System.out.println(p1.getName () + " and " + p2.getName () + " are of the same age!"); } } }
Output:
As seen from the output, we use a Comparable interface to compare two objects of the Person class based on the age member variable.
So as the name suggests, a Comparable interface allows us to compare one object with the other provided the objects are of the same type. As long as the objects know to arrange themselves, we can sort the objects easily using the sole method ‘compareTo ()’ that belongs to this interface.
Java String CompareTo () Method
We can also use the compareTo () method to compare two String type objects in Java. The two string objects are compared lexicographically by converting each character of the string object into its equivalent Unicode character.
If two strings are equal, then 0 is returned. If the first object is greater than the second object, then a positive value is returned and a negative value is returned if the first string object is lesser than the second String object.
For Example,
string1.compareTo ( string2) will compare string1 and string 2 lexicographically.
public class Main { public static void main(String args[]) { //declare and print string objects String str1 = "SoftwareTestingHelp"; String str2 = "Java Series tutorial"; String str3 = "Comparable Interface"; System.out.println("str1:" + str1); System.out.println("str2:" + str2); System.out.println("str3:" + str3); //compare strings and print the results. int retval1 = str1.compareTo( str2 ); System.out.println("\nstr1 & str2 comparison: "+retval1); int retval2 = str1.compareTo( str3 ); System.out.println("str1 & str3 comparison: "+retval2); int retval3 = str2.compareTo("compareTo method"); System.out.println("str2 & string argument comparison: "+retval3); } }
Output:
In the above program, we saw how to use the compareTo () method to compare two strings. Before that, we used the compareTo () method to compare the integer values (age for example). Similarly, we can use the other data types like doubles with the compareTo () method.
Now let’s move on to the Comparator interface in Java.
Comparator Interface In Java
We have already seen the working of the Comparable interface. The comparable interface allows us to sort custom objects based on a single data member. But when the requirement arises to sort the object based on multiple fields or data members, then we can opt for a Comparator interface.
Using the Comparator interface, we can create more than one comparator depending on how many fields we want to use to sort the custom objects. Using the comparator interface, supposing we want to sort the custom object on two member fields name and age, then we need to have two comparators, one for name and one for age.
Then we can call the Collections.sort () method with these Comparators.
So how exactly can we write the Comparators?
Consider an example of a Class Student with name and age as its field. Consider that we want to sort Student objects on name and age fields.
For this purpose, we will have to first write Comparator classes, StudentAgeComparator, and StudenNameComparator. In these classes, we will override the compare ( ) method of the Comparator interface, and then we will call the Collections.sort method using each of these comparators to sort student objects.
The comparator interface contains a ‘compare’ object that is used to compare objects of two different classes. The general syntax of the compare method is:
public int compare (Object obj1, Object obj2);
The compare method compares obj1 with obj2.
The Comparator interface is a part of the java.util package and apart from the compare method; it also contains another method named equals.
Java Comparator Example
Let’s implement a Comparator example in Java. Again we have taken a Student class with name and age as its data members. Then we define a comparator class AgeComparator that overrides the compare method to compare ages of two students and return appropriate values.
In the main method, we construct an Arraylist of Student objects. Then we call Collections.sort method with ArrayList and AgeComparator object as arguments. This sorts the Student objects according to age.
The Java program implementing this scenario is given below.
import java.util.*; //class student whose objects are to be sorted class Student{ int rollno; String name; int age; Student(int rollno,String name,int age){ this.rollno=rollno; this.name=name; this.age=age; } } //AgeComparator class implementing Comparator to compare objects class AgeComparator implements Comparator <Object> { public int compare(Object o1,Object o2){ Student s1=(Student)o1; Student s2=(Student)o2; if(s1.age==s2.age) return 0; else if(s1.age>s2.age) return 1; else return -1; } } class Main{ public static void main(String args[]){ //create an ArrayList of Students ArrayList myList=new ArrayList(); myList.add(new Student(101,"Adrian",25)); myList.add(new Student(106,"Sydney",22)); myList.add(new Student(105,"Marcus",27)); //call Collections.sort method with AgeComparator object to sort ArrayList Collections.sort(myList,new AgeComparator()); System.out.println("Sorted Student objects by Age are as follows:"); Iterator iter= myList.iterator(); while(iter.hasNext()){ Student st=(Student) iter.next(); System.out.println(st.rollno+" "+st.name+" "+st.age); } } }
Output:
In the above program, similar to the way in which we have written AgeComparator to sort the Student objects based on Age, we can also write another NameComparator to sort the Student objects based on the name field.
This way we can have as many Comparator classes as required to sort objects in various fields. The way in which we compared two int variables, we can also compare variables of the other data types using the Compare method.
Difference Between Comparable Vs Comparator
Comparable Interface | Comparator Interface |
---|---|
The comparable interface provides single field sorting. | Comparator interface provides multiple fields sorting. |
Comparable interface sorts object as per natural ordering. | Comparator interface sorts various attributes of different objects. |
Using a comparable interface we can compare the current object ‘this’ with the specified object. | Using a comparator interface, we can compare objects of different classes. |
Part of the java.lang package. | Part of java.util package. |
The use of a Comparable interface modifies the actual class. | Comparator does not alter the original class. |
Provides compareTo () method to sort elements. | Provides compare () method to sort elements. |
Uses Collections.sort (List) to sort elements. | Uses Collections.sort (List, Comparator) to sort the elements. |
Frequently Asked Questions
Q #1) Is comparable a functional interface?
Answer: Yes, comparable is a functional interface. It declares a single abstract method, compareTo ().
Q #2) How do you make a class Comparable?
Answer: We make a class comparable by implementing the Comparable interface. Inside the class, we override the compareTo () method to sort the object. We pass an object and compare it with the current object.
The method compareTo () returns 0 if two objects are equal. It returns a negative number if the first object is less than the second and positive if the first object is greater than the second object.
Q #3) What is the main purpose of the Comparator interface?
Answer: Comparator interface is mainly used to sort the custom objects. A comparator interface can be used to compare objects of different classes as well. Also, the comparator interface can be used to sort objects in multiple fields.
Q #4) Why is Comparator used in Java?
Answer: Comparator interface is mainly used when we want a different sorting order for our custom objects other than natural ordering based on multiple fields.
Q #5) What implements the Comparable interface?
Answer: Comparable interface is implemented by all the wrapper classes and String class. Custom objects also use the comparable interface for sorting.
Conclusion
In this tutorial, we have discussed comparable and comparator interfaces in Java. A comparable interface is used to sort the objects as per natural ordering and at a time can sort the objects only on one field.
The comparable interface has a method ‘compareTo ()’ that needs to be overridden in the class implementing the Comparator interface and whose objects are to be sorted.
The Comparator interface is used to sort custom objects that are to be sorted based on any other order. The comparator interface also allows us to sort objects of two different classes based on multiple fields.
=> Read Through The Easy Java Training Series.