What is the difference between Comparator and Comparable in java?


This interface comes from the java.lang package. When a class implements this interface , the class imposes a natual
order for itself and comparison scheme with the method compareTo.
List of objects which implements this interface are automatically gets sorted using Collections.sort method i.e. These objects become comparable e.g. Sorting of an arraylist of objects
Normally all core java classes implements the Comparable interface such as String, BigDecimal, Long, Integer, URI etc.

Comparable lets class instance to test itself with other instance. Comparable is used in the same class and can have only one implementation which
is normally a natural order comparison.
compareTo method of this interface compares this object with another object and returns a integer value as positive, negative or zero when this
object is greater than, less than or equal to the specified object respectively.

So normally we can use Comparable when object is in our control and only one comparing behaviour we need to compare the objects.

Comparator :

This interface comes from the java.util package. Comparator interface is used to compare values of two objects and sort the objects with control. We can pass the Comparator to the Collections.sort method to control the sort order by defining the sorting methods using Comparator interface. This interface is also used to control the sorting mechanism in TreeMap and TreeSet collections.

Comparator interface contains two methods : compare and equals

compare method takes two objects and check both the objects for their order. This method also returns positive, negative integer or zero when first object is greater than, less than or equal with second object respectively.

equals method returns true when if object itself is Comparator and have same ordering scheme as with another Comparator otherwise return false.

We can use Comparator when we need control over the sorting method of the objects on which we do not have direct control.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment