Comparable Interface

Comparable Interface

It is available in java.lang package. This interface contains only one method compareTo().

public int compareTo(Object obj)

E.g

obj1.compareTo(obj2)

returns

 –ve if obj1 has to come before obj2.
 +ve if obj1 has to come after obj2.
 0 if obj1 and obj2 are equal(Duplicate Objects).
package com.ashok.collections;

public class MyComparable {
   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
   }
}

Note

  • While Inserting the objects into the TreeSet JVM internally uses compareTo() method if we are depending on natural sorting order.
  • Sometimes we have to define our own customized sorting order, then we should go for comparator Interface.
Comparable Interface
Scroll to top