Comparable Interface in java

Comparable Interface in java Comparable interface is used to order the objects of user-defined class.This interface is found in java.lang package and contains only one method named compareTo(Object).Comparator interface provide a method name CompareTo(). This method is used to define sorting order of a class.

Comparable Interface provide only one method

public int compareTo(Object obj): is used to compare the current object with the specified object.

Returns 0 if both objects are same

+ve integer if invoking object comes after parameter object.

-ve integer if invoking object comes before parameter object

Note- String is a Comparable class that is Comparable interface is implemented in String class and sorting order of any 2 string can be obtained.

Method of Collections class for sorting List elements

public void sort(List list): is used to sort the elements of List.List elements must be of Comparable type.

Note: String class and Wrapper classes implements the Comparable interface.So if you store the objects of string or wrapper classes, it will be Comparable.

Limitation of Comparable Interface

Using the comparable interface only single sorting order can be define. In real scenario multiple sorting order is required in such a case Comparator Interface is used.