Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

JAVA 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:

ComparableDemo.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.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext