What is a Comparable Interface?

What is a Comparable Interface?

What is a comparable interface – Coders can also order objects using java comparable interface. And rather than any type of class for that object. As a result, java uses user-defined class for this interface.

You can find java comparable interface inside the java.lang package since it is located inside that package. Therefore it contains only 1 method which seems like to be CompareTo(objects). Furthermore the interface provides single sorting element on a single data member only. So For an example it may be rollno, name, age or anything else.

compareTo(Object obj) method

Therefore to compare the current object with the specified object we used the syntax :

public int compareTo(Object obj)

Hence, Here is a list of what the element we can sort :

  1. String objects
  2. User-defined class objects
  3. Wrapper class objects

As a result, now we can finally create an example of compareTo method :

import java.util.*; 
import java.io.*; 
public class compareToExmpl{ 
public static void main(String args[]){ 
ArrayList<Students> al=new ArrayList<Students>(); 
al.add(new Students(110,"Jessica",25)); 
al.add(new Students(153,"Adam",26)); 
al.add(new Students(146,"Grace",23)); 
 
Collections.sort(al); 
for(Students std:al){ 
System.out.println(std.rollno+" "+std.name+" "+std.age); 
} 
} 
}

And now it will finally output this :

110 Jessica 25

153 Adam 26

146 Grace 23

I guess that is most of allĀ  I can explain about What is Comparable Interface and if you want to know more about java, just explore craftingez6-coding.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.