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

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last