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

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...

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...