Difference between Comparable and Comparator in java
Difference between Comparable and Comparator in java is an important interview question for every Java Developer because interviewer want to know your level of expertise in Collection Framework.
|Comparable interface provides natural order sorting order by default.||Comparator interface provides customized sorting order.|
|Comparable interface present in java.lang package.||Comparator interface present in java.util package.|
|Comparable contains only one method compareTo() method.||Comparator contain two method compare() and equals() method.|
|All wrapper classes like Integer, Float etc and String class implemented Comparable interface.||Collator and RuleBasedCollator are implemented by Comparator interface.|
|Comparable should be used when you compare instances of same class.||Comparator can be used to compare instances of different classes.|
|A comparable object is capable of comparing itself with another object.||A comparator object is capable of comparing two different objects.|
|We need to modify class code if we want to change sorting logic in case of Comparable.||We no need to modify the existing class we can create another class to change sorting logic.|
Comparablemeans “We can compare myself with another object.” This is typically useful when there’s a single natural default comparison.
Comparatormeans “I can compare two other objects.” This is typically useful when there are multiple ways of comparing two instances of a type – e.g. you could compare people by age, name etc.