Categories: Java

Comparable Interface in Java

The Comparable interface is used to compare an object of the same class with an instance of that class; it also enables data ordering for user-defined class objects. The class has to implement the java.lang.Comparable interface to compare its instance, it provides the compareTo() method, which accepts an object of that class as an argument.

Its sorting algorithm is determined by the type of object used by the interface.

  • If the object type is a string, it is sorted lexicographically.
  • Else, If the object type is a wrapper class object, such as an integer or a list, the values are sorted.
  • If the object type is custom, such as a user-defined object, then it is sorted using the compareTo() method.

Collections.sort() can be used to sort classes that implement this interface automatically. Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set without requiring a comparator to be specified.

Declaration:
public interface Comparable<T>
compareTo(Object obj) method:
public int compareTo(Object obj)
  • It compares the current object to the provided object.
  • If the current object is greater than the requested object, it returns a positive integer.
  • Furthermore, If the current object is less than the given object, a negative integer is returned.
  • If the current object is equal to the requested object, the value is zero.
Example: Sorting User-Defined Object

import java.util.*;  

class Coderz implements Comparable <Coderz>
{
    int Id;
    String name;
    public Coderz (int Id, String name)
    {
        this.Id=Id;
        this.name=name;
    }
    public String toString()
    {
        return this.Id + " " + this.name;
    }

     // Sorting by Id
    public int compareTo(Coderz std){    
         // we compare
        return this.Id - std.Id; 
    } 
}

public class Demo {  
    public static void main(String a[]){
      ArrayList <Coderz> list = new ArrayList <Coderz> ( ); 
        list.add(new Coderz(2, "Rabecca")); 
        list.add(new Coderz(1, "Alan")); 
        list.add(new Coderz(3, "Ron")); 

        // Displaying
        for (int i=0; i<list.size(); i++) 
            System.out.println(list.get(i)); 
  
        // Sorting 
        Collections.sort(list); 

        // Displaying after sorting
        System.out.println("\nAfter Sorting :\n");
        for (int i=0; i<list.size(); i++) 
            System.out.println(list.get(i)); 
    }  
}
  
Output:
2 Rabecca
1 Alan
3 Ron

After Sorting :

1 Alan
2 Rabecca
3 Ron

Note: also read about the Collections Class in Java

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago