«Back to Home

Core Java

Topics

Comparable Interface In Java

Comparable Interface
 
In Java, comparable interface orders the objects of user-defined class. This interface is found in java.lang package and contains only one compareTo(Object) method. It provides the single sorting sequence only i.e. we can sort the elements, based on the single data member only.
 
Method

public int compareTo(Object obj)

This method is used to compare the current object with the particular object.
 
In Java, String class and Wrapper classes implements the comparable interface by default. Thus, if we store the objects of string or wrapper classes in the list, set or map, it will be comparable by default.
 
Let’s see an example, given below.
 
Code
  1. public class Employee implements Comparable < Employee > {  
  2.     int empId;  
  3.     String empName;  
  4.     int empAge;  
  5.     Employee(int empId, String empName, int empAge) {  
  6.         this.empId = empId;  
  7.         this.empName = empName;  
  8.         this.empAge = empAge;  
  9.     }  
  10.     public int compareTo(Employee e) {  
  11.         if (empAge == e.empAge) {  
  12.             return 0;  
  13.         } else if (empAge > e.empAge) {  
  14.             return 1;  
  15.         } else {  
  16.             return -1;  
  17.         }  
  18.     }  
  19. }  
  1. import java.util.*;  
  2. import java.io.*;  
  3. public class CollectionSort {  
  4.     public static void main(String args[]) {  
  5.         ArrayList < Employee > a = new ArrayList < Employee > ();  
  6.         a.add(new Employee(161"Harray"29));  
  7.         a.add(new Employee(146"Lucy"35));  
  8.         a.add(new Employee(175"Jack"25));  
  9.         Collections.sort(a);  
  10.         for (Employee e: a) {  
  11.             System.out.println(e.empId + " " + e.empName + " " + e.empAge);  
  12.         }  
  13.     }  
  14. }  
5

6

Output

7

In the example, shown above of the comparable interface, which sorts the list elements on the basis of age.
 
Summary

Thus, we learnt that Java comparable interface orders the objects of user-defined class. This interface is found in java.lang package and contains only one compareTo(Object) method. We also learnt how to create it in Java.