Open In App

Java Comparable Interface

Last Updated : 17 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 interfaceto sort integers.

Java
importjava.util.*;classNumberimplementsComparable<Number>{intv;// Value of the number// ConstructorpublicNumber(intv){this.v=v;}// toString() for displaying the number@OverridepublicStringtoString(){returnString.valueOf(v);}// compareTo() method to // define sorting logic@OverridepublicintcompareTo(Numbero){// Ascending orderreturnthis.v-o.v;}publicstaticvoidmain(String[]args){// Create an array of Number objectsNumber[]n={newNumber(4),newNumber(1),newNumber(7),newNumber(2)};System.out.println("Before Sorting: "+Arrays.toString(n));// Sort the arrayArrays.sort(n);// Display numbers after sortingSystem.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.

Java
importjava.util.*;classPairimplementsComparable<Pair>{Strings;// String intv;// Integer // Constructor publicPair(Strings,intv){this.s=s;this.v=v;}// toString() method for // displaying the Pair@OverridepublicStringtoString(){return"("+s+", "+v+")";}// compareTo() method for // comparison logic@OverridepublicintcompareTo(Pairp){// Compare based on the string field // (lexicographical order)if(this.s.compareTo(p.s)!=0){returnthis.s.compareTo(p.s);}// If strings are the same, // compare based on the integer valuereturnthis.v-p.v;}publicstaticvoidmain(String[]args){// Create an array of // Pair objectsPair[]p={newPair("abc",3),newPair("a",4),newPair("bc",5),newPair("a",2)};System.out.println("Before Sorting:");for(Pairp1:p){System.out.println(p1);}// Sort the array of pairsArrays.sort(p);System.out.println("\nAfter Sorting:");for(Pairp1: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.

Java
importjava.util.*;classPairimplementsComparable<Pair>{Stringf;// First nameStringl;// Last name// Constructor publicPair(Stringf,Stringl){this.f=f;this.l=l;}// toString() method // for displaying the Pair@OverridepublicStringtoString(){return"("+f+", "+l+")";}// compareTo method for // comparison logic@OverridepublicintcompareTo(Pairp){// Compare based on the first name // (lexicographical order)if(this.f.compareTo(p.f)!=0){returnthis.f.compareTo(p.f);}// If first names are the same, // compare based on the last namereturnthis.l.compareTo(p.l);}publicstaticvoidmain(String[]args){// Create an array of Pair objectsPair[]p={newPair("raj","kashup"),newPair("rahul","singh"),newPair("reshmi","dubey"),};System.out.println("Before Sorting:");for(Pairp1:p){System.out.println(p1);}// Sort the array of pairsArrays.sort(p);System.out.println("\nAfter Sorting:");for(Pairp1: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

close