Thursday, January 16, 2025
HomeGeneralDifference between Comparable and Comparator

Difference between Comparable and Comparator

In Java, Comparable and Comparator are interfaces used to define sorting logic for objects.

Comparable is used for natural ordering and is implemented directly by the class. It requires the class to implement the compareTo() method, which defines how objects of that class should be compared. Example: Collections.sort(list)uses compareTo() if objects implement Comparable.

Comparator, on the other hand, provides custom sorting logic. It is implemented as a separate class or lambda expression. The compare() method is used to define sorting between two objects. Example: Pass a Comparator to Collections.sort(list, comparator) for customized sorting logic.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x