Open In App

Java Comparable Interface

Last Updated : 17 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The Comparable interface in Java is used to define the natural ordering of objects for a user-defined class. It is part of the java.lang package and it provides a compareTo() method to compare instances of the class. A class has to implement a Comparable interface to define its natural ordering.

Example 1: Here, we will use the Comparable interface to sort integers.

import java.util.*;

class Number implements Comparable<Number> {
    int v; // Value of the number

    // Constructor
    public Number(int v) {
        this.v = v;
    }

    // toString() for displaying the number
    @Override
    public String toString() {
        return String.valueOf(v);
    }

    // compareTo() method to 
    // define sorting logic
    @Override
    public int compareTo(Number o) {
      
        // Ascending order
        return this.v - o.v; 
    }

    public static void main(String[] args) {
      
        // Create an array of Number objects
        Number[] n = { new Number(4), new Number(1), 
                      new Number(7), new Number(2) };

        System.out.println("Before Sorting: " 
                           + Arrays.toString(n));

        // Sort the array
        Arrays.sort(n);

        // Display numbers after sorting
        System.out.println("After Sorting: " + Arrays.toString(n));
    }
}

Output
Before Sorting: [4, 1, 7, 2]
After Sorting: [1, 2, 4, 7]

Explanation: In the above example, the compareTo() method is overridden to define the ascending order logic by comparing the v fields of Number objects. Then the Arrays.sort() method sorts the array by using this logic.

Declaration of Comparable Interface

public interface Comparable<T> {

int compareTo(T obj);

}

where, T is the type of object which to be compared.

  • It compares the current object with the specified object.
  • It returns:
    • Negative, if currentObj < specifiedObj.
    • Zero, if currentObj == specifiedObj.
    • Positive, if currentObj > specifiedobj.

Use of Comparable Interface

  • In this method, we are going to implement the Comparable interface from java.lang Package in the Pair class.
  • The Comparable interface contains the method compareTo to decide the order of the elements.
  • Override the compareTo method in the Pair class.
  • Create an array of Pairs and populate the array.
  • Use the Arrays.sort() function to sort the array.

Example 2: Sorting Pairs with String and Integer Fields

Given an array of Pairs consisting of two fields of type string and integer. Now, we have to sort the array in ascending Lexicographical order and if two strings are the same, sort it based on their integer value.

import java.util.*;

class Pair implements Comparable<Pair> {
    String s; // String 
    int v;    // Integer 

    // Constructor 
    public Pair(String s, int v) {
        this.s = s;
        this.v = v;
    }

    // toString() method for 
    // displaying the Pair
    @Override
    public String toString() {
        return "(" + s + ", " + v + ")";
    }

    // compareTo() method for 
    // comparison logic
    @Override
    public int compareTo(Pair p) {
      
        // Compare based on the string field 
        // (lexicographical order)
        if (this.s.compareTo(p.s) != 0) {
            return this.s.compareTo(p.s);
        } 
      
        // If strings are the same, 
        // compare based on the integer value
        return this.v - p.v;
    }

    public static void main(String[] args) {
      
        // Create an array of 
        // Pair objects
        Pair[] p = {
            new Pair("abc", 3),
            new Pair("a", 4),
            new Pair("bc", 5),
            new Pair("a", 2)
        };

        System.out.println("Before Sorting:");
        for (Pair p1 : p) {
            System.out.println(p1);
        }

        // Sort the array of pairs
        Arrays.sort(p);

        System.out.println("\nAfter Sorting:");
        for (Pair p1 : p) {
            System.out.println(p1);
        }
    }
}

Output
Before Sorting:
(abc, 3)
(a, 4)
(bc, 5)
(a, 2)

After Sorting:
(a, 2)
(a, 4)
(abc, 3)
(bc, 5)

Note: if two strings are the same then the comparison is done based on the value.

Example 3: Sorting Pairs with First and Last Names

Given an array of Pairs consisting of two strings with first and last names. Now, we have to sort the array in ascending Lexicographical order of the first name and if two strings are the same sort it based on their last name.

import java.util.*;

class Pair implements Comparable<Pair> {
    String f; // First name
    String l;  // Last name

    // Constructor 
    public Pair(String f, String l) {
        this.f = f;
        this.l = l;
    }

    // toString() method 
    // for displaying the Pair
    @Override
    public String toString() {
        return "(" + f + ", " + l + ")";
    }

    // compareTo method for 
    // comparison logic
    @Override
    public int compareTo(Pair p) {
      
        // Compare based on the first name 
        // (lexicographical order)
        if (this.f.compareTo(p.f) != 0) {
            return this.f.compareTo(p.f);
        }
      
        // If first names are the same, 
        // compare based on the last name
        return this.l.compareTo(p.l);
    }

    public static void main(String[] args) {
      
        // Create an array of Pair objects
        Pair[] p = {
            new Pair("raj", "kashup"),
            new Pair("rahul", "singh"),
            new Pair("reshmi", "dubey"),
        };


        System.out.println("Before Sorting:");
        for (Pair p1 : p) {
            System.out.println(p1);
        }

        // Sort the array of pairs
        Arrays.sort(p);

        System.out.println("\nAfter Sorting:");
        for (Pair p1 : p) {
            System.out.println(p1);
        }
    }
}

Output
Before Sorting:
(raj, kashup)
(rahul, singh)
(reshmi, dubey)

After Sorting:
(rahul, singh)
(raj, kashup)
(reshmi, dubey)


Next Article

Similar Reads

three90RightbarBannerImg