Skip to main content

Comparable Interface in Java with Examples | Programming Tutorial

How Comparable Interface works in Java? When to use Comparable Interface in Java with Examples?

What is comparable interface in java?
 
In java, we often need to compare two values. We can easily compare primitive data type values like char, int, float, double using equals (= =), Less than (<) or Greater than (>) Operators.
 
But Comparing two objects, is bit different in Java. We can use Comparable or Comparator Interface for comparing two objects in Java. Based on our requirements we can choose Comparable or Comparator Interface.
 
Learn more about Comparator Interface and How to sort list using Comparator Interface with null values :-

What is Comparable Interface in Java?

Comparable interface in Java is used to compare two objects and sort them based on natural ordering.

Comparable interface is known as natural ordering.

In simple word, Comparable interface is used for sorting object according to the natural ordering. Lists and Arrays of objects that implement Comparable interface can be sorted automatically by Collections.sort and Arrays.sort.

Comparable Interface present in java.lang package. The class whose objects you want to sort must implement comparable interface. In java, All wrapper classes and String class implements comparable interface.

Natural ordering is done by compareTo() method of Comparable interface.

Syntax:-
int compareTo(Object object)

The compareTo method required by the Comparable interface receives as its parameter the object to which the current object is compared. If the current object comes before the object received as a parameter in terms of sorting order, the method should return a negative number. If, on the other hand, the current object comes after the object received as a parameter, the method should return a positive number. Otherwise, 0 is returned.  

Following three value can returns by compareTo method.

  • Positive integer = the current object > the object parameter passed.
  • Negative integer = the current object < the specified object.
  • Zero = the current object and specified object are both equal.

For use comparable interface, we have to implement Comparable Interface in java. 

public class Demo implements Comparable<Demo>

and after we must implement compareTo() method in our java class.

After implement Comparable interface and implementing compareTo() method we can use Collections.sort() or Arrays.sort() for sorting.

  • Collections.sort() is used to sort list of objects.
  • Arrays.sort() is used to sort array of objects.

Lets see example of comparable interface so you can understand better.

Example 1 :- Sort custom Object using Comparable interface in Java

Programming.java

package Comparable;

public class Programming implements Comparable<Programming> {

    private int id;
    private String language;

    public Programming(int id, String language) {
        this.id = id;
        this.language = language;
    }
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getLanguage() {
        return language;
    }
    public void setLanguage(String language) {
        this.language = language;
    }
    
    @Override
    public String toString() {
        return "Programming [id = " + id + ", language = " + language + "]";
    }

    @Override
    public int compareTo(Programming obj) {
       
        if (this.id == obj.id) {
            return 0;
        } else if (this.id > obj.id) {
            return 1;
        } else {
            return -1;
        }
    }
    
}

ComparableDemo.java

package Comparable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparableDemo {

    public static void main(String[] args) {

        List<Programming> programmingList = new ArrayList<Programming>() {{
            add(new Programming(7, "Java"));
            add(new Programming(10, "Python"));
            add(new Programming(5, "CSharp"));
            add(new Programming(8, "JavaScript"));
            add(new Programming(2, "C"));
            add(new Programming(4, "Dot net"));
            add(new Programming(3, "C++"));
            add(new Programming(6, "Go"));
            add(new Programming(9, "Php"));
            add(new Programming(11, "ReactJs"));
            add(new Programming(1, "AngularJs"));
            add(new Programming(12, "VueJs"));
        }};
       
        System.out.println("Before Sorting");
for (Programming programming : programmingList) {
    System.out.println(programming);
}

// Sorting the custom Programming object
        Collections.sort(programmingList);

System.out.println("\nAfter Sorting");
for (Programming programming : programmingList) {
    System.out.println(programming);
}
       
    }

}

Output :-

Before Sorting
Programming [id = 7, language = Java]
Programming [id = 10, language = Python]
Programming [id = 5, language = CSharp]
Programming [id = 8, language = JavaScript]
Programming [id = 2, language = C]
Programming [id = 4, language = Dot net]
Programming [id = 3, language = C++]
Programming [id = 6, language = Go]
Programming [id = 9, language = Php]
Programming [id = 11, language = ReactJs]
Programming [id = 1, language = AngularJs]
Programming [id = 12, language = VueJs]

After Sorting
Programming [id = 1, language = AngularJs]
Programming [id = 2, language = C]
Programming [id = 3, language = C++]
Programming [id = 4, language = Dot net]
Programming [id = 5, language = CSharp]
Programming [id = 6, language = Go]
Programming [id = 7, language = Java]
Programming [id = 8, language = JavaScript]
Programming [id = 9, language = Php]
Programming [id = 10, language = Python]
Programming [id = 11, language = ReactJs]
Programming [id = 12, language = VueJs]

We can also reverse sorting on objects. Lets try with above example. 

If we want to sort above Programming objects in reverse, Simply change Greater than (>) sign to less than (<) sign in compareTo method else if condition.

We can also use Comparator in compareTo() method.

    @Override
    public int compareTo(Programming obj) {
        
        return Comparator.comparing(Programming::getId)
                  .compare(this, obj);
    }

 

Example 2 :- Reverse Custom Java Objects using Comparable Interface

package Comparable;

public class Programming implements Comparable<Programming> {

    private int id;
    private String language;

    public Programming(int id, String language) {
        this.id = id;
        this.language = language;
    }
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getLanguage() {
        return language;
    }
    public void setLanguage(String language) {
        this.language = language;
    }
    
    @Override
    public String toString() {
        return "Programming [id = " + id + ", language = " + language + "]";
    }

    @Override
    public int compareTo(Programming obj) {
        
        if (this.id == obj.id) {
            return 0;
        } else if (this.id < obj.id) {
            return 1;
        } else {
            return -1;
        }
    }

    
}

There is no need to change in ComparableDemo.java file.

Output :-

Before Sorting
Programming [id = 7, language = Java]
Programming [id = 10, language = Python]
Programming [id = 5, language = CSharp]
Programming [id = 8, language = JavaScript]
Programming [id = 2, language = C]
Programming [id = 4, language = Dot net]
Programming [id = 3, language = C++]
Programming [id = 6, language = Go]
Programming [id = 9, language = Php]
Programming [id = 11, language = ReactJs]
Programming [id = 1, language = AngularJs]
Programming [id = 12, language = VueJs]

After Sorting
Programming [id = 12, language = VueJs]
Programming [id = 11, language = ReactJs]
Programming [id = 10, language = Python]
Programming [id = 9, language = Php]
Programming [id = 8, language = JavaScript]
Programming [id = 7, language = Java]
Programming [id = 6, language = Go]
Programming [id = 5, language = CSharp]
Programming [id = 4, language = Dot net]
Programming [id = 3, language = C++]
Programming [id = 2, language = C]
Programming [id = 1, language = AngularJs]

So now lets see when we have to use Comparable interface rather than Comparator interface.

When to use Comparable interface in Java?

  • When you want to define natural or default ordering for objects.
  • Comparable should be used when you compare instances of the same class. 
  • When you want to compare object by only one property.

 

Happy Coding.

Other articles you may like :-

Comments

Popular posts from this blog

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...