Updated April 1, 2023
Introduction to Comparable in Java
In Java, a Comparable interface is an interface that helps in ordering the objects of an array or a list based on the natural order. Using this interface, it is possible to sort the elements of objects such as String objects, User-defined objects and Wrapper class objects. This interface is present in the package java.lang and consists of only one method compareTo(), which will be explained in the next section. More details such as syntax, working, and examples of the comparable interface will be discussed in the coming sections in detail.
Methods of Java Comparable
As already discussed following are the one and only method compareTo(obj) for the interface comparable.
compareTo(obj)
This method compares the object with the object obj for the order specified in it. In the practical scenario, this method will be overridden in order to return values. The return values of this method can be:
- +ve : In the case where the present object is greater than the object mentioned.
- -ve : In the case where the present object is less than the object mentioned.
- 0: In the case where the present object is equal to the object mentioned.
Syntax:
Below is the syntax of the comparable interface.
class Employee implements Comparable<Employee>
{
. . .
}
//compareTo method that has to be overridden
public int compareTo(Employee em)
{
. .
}
How Comparable Works in Java?
Suppose there is a group of students S1, S2, S3, S4 where their heights are 145, 187, 166, 172 and age is 23, 24, 21, 26. In what ways we can sort them? Height, Weight, Age, etc., right?
- Even if we compare them based on one criteria, Age, we have to repeatedly compare and sort two students until all the students age are considered. That is, is student 1 age is greater than student 2, student 2 age greater than student 3 age etc. In order to accomplish this objective, a comparable interface came into action.
- The method compareTo() in comparable interface helps in achieving it. As already discussed, this method returns either a positive, negative or zero value. So, this object will be compared with the argument object on calling this method. If the age is lesser, then a negative value will be returned. Similarly, a positive value will be returned if the age is higher.
Examples to Implement Comparable in Java
Below are the examples to understand comparable interface with the help of programs.
Example #1
Java program to create a student list and sort the elements based on the height’s natural ordering.
Code:
//Driver class
import java.util.ArrayList;
import java.util.Collections;
// Driver class
class Main
{
//main method
public static void main(String[] args)
{
//create an array list
ArrayList<Student>li = new ArrayList<Student>();
//add elements to the array list
li.add(new Student("Kukku", 45 , 162));
li.add(new Student("Kunju", 43 , 164));
li.add(new Student("Anna" , 47 , 173));
li.add(new Student("Adam" , 49 , 181));
//sort the list
Collections.sort(li);
System.out.println("After sorting, student list will be : ");
//print elements in the list one by one
for (Student st: li)
{
System.out.println(st.getName() + " " + st.getMark() + " " + st.getHeight());
}
}
}
//Student class
// Student is a class that implements Comparable
class Student implements Comparable<Student>
{
private int mark;
private String name;
private int height;
// sort students based on mark
public int compareTo(Student s)
{
return this.height - s.height;
}
// Constructor of the class
public Student(String nam, int ag, int hght)
{
this.name = nam;
this.mark = ag;
this.height = hght;
}
// To access private methods, create get methods
public double getMark()
{
return mark;
}
public String getName()
{
return name;
}
public int getHeight()
{
return height;
}
}
Output:
Explanation:
A student list is created first in the above program, and elements are sorted based on their height. The parameter that has to be compared is mentioned inside the compareTo() method. If the marks of the students have to be compared, only the parameter inside the method has to be changed.
Example #2
Java program to create a student list and sort the elements based on reverse order of the height.
Code:
//Driver class
import java.util.ArrayList;
import java.util.Collections;
// Driver class
class Main
{
//main method
public static void main(String[] args)
{
//create an array list
ArrayList<Student>li = new ArrayList<Student>();
//add elements to the array list
li.add(new Student("Kukku", 45 , 162));
li.add(new Student("Kunju", 43 , 164));
li.add(new Student("Anna" , 47 , 173));
li.add(new Student("Adam" , 49 , 181));
//sort the list
Collections.sort(li, Collections.reverseOrder());
System.out.println("After sorting, student list will be : ");
//print elements in the list one by one
for (Student st: li)
{
System.out.println(st.getName() + " " + st.getMark() + " " + st.getHeight());
}
}
}
//Student class
// Student is a class that implements Comparable
class Student implements Comparable<Student>
{
private int mark;
private String name;
private int height;
// sort students based on mark
public int compareTo(Student s)
{
return this.height - s.height;
}
// Constructor of the class
public Student(String nam, int ag, int hght)
{
this.name = nam;
this.mark = ag;
this.height = hght;
}
// To access private methods, create get methods
public double getMark()
{
return mark;
}
public String getName()
{
return name;
}
public int getHeight()
{
return height;
}
}
Output:
Explanation:
In this program, similar to the first program, a student list is created first, and elements are sorted based on their height. The difference between the first example and this program is the ordering of the elements. In this program, reverse ordering is done using the method reverseOrder(), and the elements are printed based on it.
Conclusion
A comparable interface in Java is an interface that orders the objects of an array or a list based on the natural order. This is done with the help of a method compareTo() that overrides based on the user’s requirement. In this article, different aspects such as syntax, working and example of the comparable interface are discussed in detail.
Recommended Article
This is a guide to Comparable in Java. Here we discuss the Introduction to Comparable in Java and top Methods along with examples as well as Code Implementation. You can also go through our other suggested articles to learn more –