Comparable interface

• Comparable interface present in java.lang package and contains only one method compareTo() method.
public int compareTo(Object obj);
Example:
obj1.compareTo(obj2);
Diagram:
comparableinterface

Example :
class Test
{
public static void main(String[] args)
{
System.out.println(“A”.compareTo(“Z”));//-25
System.out.println(“Z”.compareTo(“K”));//15
System.out.println(“A”.compareTo(“A”));//0
//System.out.println(“A”.compareTo(new Integer(10)));//Test.java:8: compareTo(java.lang.String) in java.lang.String cannot be applied to (java.lang.Integer)
//System.out.println(“A”.compareTo(null));//NullPointerException
}
}
Example :
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet t=new TreeSet();
t.add(10);
t.add(0);
t.add(15);
t.add(10);
System.out.println(t);//[0, 10, 15]
}
}
compareTo() method analysis:
conpareto
• If we are not satisfying with default natural sorting order (or) if default natural sorting order is not available then we can define our own customized sorting by Comparator object.
• Comparable meant for default natural sorting order.
• Comparator meant for customized sorting order.

Leave a Reply

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