Javatpoint Logo
Javatpoint Logo

Difference between Comparable and Comparator

Comparable and Comparator both are interfaces and can be used to sort collection elements.

However, there are many differences between Comparable and Comparator interfaces that are given below.

ComparableComparator
1) Comparable provides a single sorting sequence. In other words, we can sort the collection on the basis of a single element such as id, name, and price. The Comparator provides multiple sorting sequences. In other words, we can sort the collection on the basis of multiple elements such as id, name, and price etc.
2) Comparable affects the original class, i.e., the actual class is modified.Comparator doesn't affect the original class, i.e., the actual class is not modified.
3) Comparable provides compareTo() method to sort elements.Comparator provides compare() method to sort elements.
4) Comparable is present in java.lang package.A Comparator is present in the java.util package.
5) We can sort the list elements of Comparable type by Collections.sort(List) method.We can sort the list elements of Comparator type by Collections.sort(List, Comparator) method.

Java Comparable Example

Let's see the example of a Comparable interface that sorts the list elements on the basis of age.

File: TestSort3.java

Test it Now

Output:

105 Jai 21
101 Vijay 23
106 Ajay 27

Java Comparator Example

Let's see an example of the Java Comparator interface where we are sorting the elements of a list using different comparators.

Student.java
AgeComparator.java
NameComparator.java

This class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic.

TestComparator.java

In this class, we are printing the values of the object by sorting on the basis of name and age.

Output:

Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23

Sorting by Age       
105 Jai 21
101 Vijay 23
106 Ajay 27
Next TopicProperties in Java





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA