Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Comparable

Declaration

interface Comparable<T>

The Comparable interface is present in java.lang package.

Comparable interface is implemented by many classes so that objects of implementing classes can be ordered properly.

It contains only one method known as compareTo(). This method is used to compare two objects of same class which implements Comparable interface.

Java Programming Language Comparable Interface Method

Java Programming Language Comparable Interface Comparison

Example

 class ComparableDemo
 {
     public static void main(String args[])
     {
         Integer i1 = 10;
         Integer i2 = 20;
		
         String s1 = new String("A");
         String s2 = new String("B");
		
         StringBuffer sb1 = new StringBuffer("X");
         StringBuffer sb2 = new StringBuffer("Y");
		
         System.out.println(i1.compareTo(i2));
         System.out.println(i2.compareTo(i1));
         System.out.println(i1.compareTo(i1));
         System.out.println();
         System.out.println(s1.compareTo(s2));
         System.out.println(s2.compareTo(s1));
         System.out.println(s2.compareTo(s2));
         System.out.println();
    //   System.out.println(sb1.compareTo(sb2));
    //   System.out.println(sb2.compareTo(sb1));
    //   System.out.println(sb2.compareTo(sb2));
    }
 }

Output

-1
1
0

-1
1
0

In the above program, we have used compareTo() method of Comparable interface to compare Integer & String object.
Thus the result is same as explained before the program.

In the above program, we are able to compare objects of only Integer & String class and not StringBuffer class because Integer & String class implements Comparable interface whereas StringBuffer does not implement the Comparable interface.
Therefore if we removed the comments of the last three lines where StringBuffer objects are compared, we will get compile time error saying, The method compareTo(StringBuffer) is undefined for the type StringBuffer.

 

Leave a reply