Comparable and Comparator in Java

Comparable and Comparator in Java:

What is Comparable and Comparator?
Comparable is an interface used for sorting the objects. It supports Single sorting only.
Comparator is an interface used for Sorting, but supports multiple sorting.

Difference Between Comparable and Comparator:

Comparable Comparator
Compatable interface is used for Single sorting and overrides CompareTo() Comparator interface is used for Multiple Sorting and overrides Compare()
java.lang.Comparable java.util.Comparator


Comparable Example:
In comparable, We select a single object and compare with others to sort it. In this example, We are going to select one number and compare it with other numbers and sort them.

 

Output:

comparable

Comparator Example:
In comparator, We select two objects and compare them with each other and make the sort.

Output:
comparator

 

 

Read More