Comparable Interface

  • Comparable interface present in java.lang package.
  • It contains only one method, that is compareTo() method.

Example:

obj1.compareTo(obj2);

  • Returns ?ve, if ob1 have to come before ob2.
  • Returns +ve, if ob1 have to come after ob2.
  • Returns 0, if ob1 and ob2 are equal.

Let's see a demo program of compareTo() method:

TreeSetDemo2.java

import java.util.*;
class ComparableDemo
{
public static void main(String args[])
{
System.out.println("A".compareTo("Z"));
System.out.println("Z".compareTo("B"));
System.out.println("A".compareTo("A"));
System.out.println("A".compareTo(null));
}
}

Output

-25
24
0

Note

  • If we are depending on the default natural sorting order, internally JVM will call to compareTo() method will inserting objects to the TreeSet. Hence the objects should be Comparable.

    TreeSet t=new TreeSet();
    t.add("B");
    t.add("Z"); //'Z'.compareTo("B"); +ve
    t.add("A"); //'A'.compareTo("B"); -ve
    System.out.println(t); //[A,B,Z]

  • If we are not satisfied with default natural sorting order or if the default natural sorting order is not available then we can define our own customized sorting by using Comparator interface.
  • Comparable is used for default natural sorting order where as Comparator is used for Customized sorting order.

 

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment