Comparable and Comparator, both being interfaces, play a crucial role in sorting elements. This article will delve into the key differences between Comparable and Comparator in Java.
Overview
Test Series
Comparable and Comparator, both being interfaces, play a crucial role in sorting elements. This article will delve into the key differences between Comparable and Comparator in Java.
In Java, Comparable refers to an object that can be compared with other objects. Numerous built-in classes in Java implement the Comparable interface.
Get 12 Months Banking & Insurance Super Pack SuperCoaching @ just
₹5998₹2179
The Comparator interface in Java is used for ordering the objects of user-defined classes. It has the ability to compare two objects of the same class.
S.No. | Comparable | Comparator |
---|---|---|
1. | It allows sorting based on a single attribute. We can sort the collection based on a single element. | It allows sorting based on multiple attributes. In this case, we can sort the collection based on multiple elements. |
2. | It uses the compareTo() method to sort elements. | It uses the compare() method to sort elements. |
3. | It doesn't modify the original class. | It also doesn't modify the original class. |
4. | It is part of the java.lang package. | It is part of the java.util package. |
Stay updated with the latest information on GATE Exam , including GATE Eligibility Criteria , GATE 2023 , GATE Admit Card , GATE Application Form , GATE Syllabus , GATE Cut off , GATE Previous Year Question Paper , and more.
Also Explore,
Download the Testbook APP & Get Pass Pro Max FREE for 7 Days
Download the testbook app and unlock advanced analytics.