Comparable vs Comparator


Comparators and Comparables

As both names suggest (and you may have guessed), these are used for comparing objects in Java. Using these concepts; Java objects can be sorted according to a predefined order.

Two of these concepts can be explained as follows.

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

How to use these?
There are two interfaces in Java to support these concepts, and each of these has one method to be implemented by user.
Those are;

java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.


Comparator - is  useful when using the classes from the jar file, not allowed to modify the classes. This is used to sort the collections.
 Collections.sort(list, new CoreTeamPlayerScoreComparator());

Comparable - Used to compare the our own classes(so by implementing the Comapable interface).
  1. positive – this object is greater than o1
  2. zero – this object equals to o1
  3. negative – this object is less than o1


java.util.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.

  1. positive – o1 is greater than o2
  2. zero – o1 equals to o2
  3. negative – o1 is less than o1

java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.
java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.


Note- Java exposes these two types comapre methods/interface.
Comparable: Used to compare the one object with the other one by implementing the (Class to be modified by extending) Comparable interface.
Comparator: Used to compare the one object with the other one by implementing the (Without modifying the Class) Comparator interface. Comparator is used to sort the collections or arrays by creating the Comparator.