67. Compare Comparable and Comparator Inteface?

Compare Comparable and Comparator Inteface?

For object type, if you want to sort the elements in a collection, you need to provide a comparator. There are two way to provide comparator for collection : Comparable and Comparator interface.

Here is some different point between Comparable and Comparator interface:

 

Comparable

Comparator
Comparable provides only one way of comparison. That is, we can only compare by id or name, or age, … Comparable provides a variety of comparisons. That is, we can sort based on many factors such as id, name, age, …
Comparable modifies the original class, that is, the comparable object’s class must modify and implement the Comparable Interface to implement. Comparator does not change the original class. We can create a new class that implements the Comparator Interface to implement.
Comparable provides compareTo() method to compare two elements. Comparator provides compare() method to compare two elements.
Any list can be sorted using the Collections.sort(List) method . Any list can be sorted using the Collections.sort(List, Comparator) method

Leave a Reply

Your email address will not be published. Required fields are marked *