Java – Comparable v/s Comparator

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

  1. Comparable interface
  2. Comparator interface

Both interface is used to sort collection elements

1. Comparable v/s Comparator:

Comparable interfaceComparator interface
Present in java.lang packagePresent 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 requiredSeparate class is required to implement Comparator interface
Elements of List can be sorted using comparable interface using sort(); method of Collections class, as shown below

 

Example: Collection.sort(listItems);

Elements of List can be sorted using comparator interface using sort(); method of Collections class, as shown below

 

Example: Collection.sort(listItems, comparator);

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

2. Example on Comparable and Comparator interface:

  1. Comparable interface
  2. Comparator interface

Related Articles :

References:

Happy Coding !!
Happy Learning !!

Java - Map interface with method details
Java - Comparator interface with example