
You can use both the Comparable and Comparator for the sorting of the collection in Java. The Comparable itself compares two elements, but in case of comparator you need to create a sub-class and implement this interface. For this you need to write your own sorting code. Furthermore, we will discuss the difference between Comparator and Comparator in detail and in which package this interface is present and what methods are available in those interfaces.
Table of Contents
Comparable Interface in Java
Comparable defines a way to sort elements based on only one field, if we are referencing a user-defined class as an element. A user-defined class can have multiple fields but we can use only one field in comparison.
compare(Object obj) method
On the basis of comparison like greater than, less than and equal this method returns some number.
- Returns +ve number, if the current object is greater than the provided object.
- Returns -ve number, if the current object is less than the provided object.
- If the current object is equal to the specified object then method will return 0.
Comparator Interface in Java
If you have to write your own sorting code then you should use Comparator interface which will help you to customize your sorting order. Hence, you can sort the collections based on multiple fields if you are going to sort collection which contains user-defined class.
Comparable Vs Comparator
Here is the main difference between Comparable and Comparator are as follow:
# | Comparable | Comparator |
---|---|---|
1 | Comparable interface is used to sort the objects with natural ordering. | But Comparator is meant for customize sorting order. |
2 | Comparable interface compares current object (using “this”) reference with the specified object. | But Comparator in Java compares two different class objects. |
3 | Comparable is present in java.lang package. | But Comparator is present in the java.util package. |
4 | Comparable has compareTo() method to sort elements. | But Comparator has compare() method to sort elements. |
5 | Comparable affects the original class, i.e., which is modified. | But Comparator does not affect the original class. |
6 | Collections.sort(List) method can be used to sort the list elements of Comparable type. | But Collections.sort(List, Comparator) method can be used to sort the list elements of Comparator type. |
Recommended Article
- Difference Between Callable Interface and Runnable Interface
- Difference between structured data and unstructured data
- final, finally and finalize difference
- StringBuilder Vs StringBuffer in Java
- Difference between Abstract Class and Interface
- Memory Allocation – Stack Memory Vs Heap Memory
In conclusion, hope you have learned about difference between comparable and comparator. Feel free to contact us on this link.