Comparable v/s Comparator

In this article, we will compare 2 important interfaces in collection framework i.e.; Comparable v/s Comparator

  1. Comparable interface
  2. Comparator interface

Both interface is used to sort collection elements


Comparable v/s Comparator:

Comparable interface Comparator interface
Present in java.lang package Present in java.util package
Defines only one important method i.e.;

public int compareTo(Object obj);

Defines 2 method i.e.;

public int compare(Object obj1, Object obj2);

public boolean equals(Object object);

It is basically used for default natural sorting order [DNSO] This is preferred for customized sorting order [CSO]
This interface need to be implemented in the same class for which sorting is required Separate class is required to implement Comparator interface
Elements of List can be sorted using comparable interface

Example: Collection.sort(listItems);

Elements of List can be sorted using comparator interface

Example: Collection.sort(listItems, comparator);

String & wrapper classes’ like Integer, Double, etc implement comparable interface There are very few classes’ which implements Comparator interface


Example on Comparable and Comparator interface:

  1. Comparable interface
  2. Comparator interface




Happy Coding !!
Happy Learning !!