Comparable vs Comparator in java

Comparable interface is used to define natural ordering of the class. This interface found in the java.lang package.

public interface Comparable<T> {
    public int compareTo(T o);
}

Here is the breakdown how it works.
Purpose:- The Comparable interface is used to impose a total ordering on instance of a class.
This allow object of that class to be compared and sorted.

Method:- The compareTo() method compares the current object(this) with another object (o) of the same type(T). It return negative integer, zero and positive integer if the current object is less than, equalsTo or greater than the specified object respectively.

Comparator

Comparator interface used to define custom ways of comparing objects.
It is typically used as separate class or as a lambda expression.
It defines a method compare() which compares two objects.

Usage of Comparator interface:- They are specially useful when you want to sort objects when by multiple attributes or when you want to sort objects of a class that you can not modify eg third party libraries.

src code link

Author: Susheel kumar

Leave a Reply

Your email address will not be published. Required fields are marked *