Monday, June 8, 2020

Differences between Comparable and Comparator


Both Comparable and Comparator or interfaces used to sort Collection elements. Both have one ,one method compareTo() and compare() to provide sorting and these are very useful in case of sorting .

ComparableComparator
Comparable interface is found in java.lang package.Comparator interface is present in java.util package.
It provides one method named compareTo()It provides one method named compare()
Comparable provides only one sort of sequence.Comparator provides multiple sorts of sequences
If we implement the Comparable interface, the actual class is modified.The actual class is not changed.
Comparable interface compares “this” reference with the object specifiedComparator in Java compares two different class objects provided.
Comparable interface is used to sort the objects with natural ordering.Comparator in Java is used to sort attributes of different objects.

No comments:

Post a Comment

Hello Buddy, if you have any doubts or need any clarification , feel free to comment. Thanks.