Comparable Interface

While writing the object-oriented programs, comparison of two instances of the same class is often required.

Comparable Interface

Comparable Interface

     

While writing the object-oriented programs, comparison of two instances of the same class is often required. Once instances are comparable, we can sort them in any order. Comparable interface is defined in java.lang package and is used to define the natural sort order of a class. While the interface java.lang.Comparator defines an auxiliary sort order for a class. 

Comparable interface can be implemented by implementing only one method: compareTo. Implement the existing class by defining the the natural order of that class. compareTo() method compares the two object of same type and returns a numerical result based on the comparison. If the result is negative, then the object sorts less than the other; if 0, the two are equal, and if positive, this object sorts greater than the other. To translate this into boolean, simply performs object1.compareTo(object2) <op> object,  where op is one of <, <=, =, !=, >, or >=.

public int compareTo( Object o );

Implemented Classes: Classes implemented by this interface are Boolean, Byte, Character, Double, Enum, Float, Integer, Long, Short, String.