Explain the difference between Comparator and Comparable in Java.
Explain the difference between Comparator and Comparable in Java.
Student
The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
ComparatorandComparableare both interfaces used to define the natural ordering of objects and provide ways to compare objects. However, they have different purposes and are used in different contexts.Comparable
Comparableis an interface in Java used to define the natural ordering of objects of a class. A class that implements theComparableinterface needs to override thecompareTomethod to specify how objects of that class should be compared.Key Characteristics:
compareTomethod, defining a single sorting sequence.compareTo(Object o).java.langpackage.Usage Example: Here's how you can use
Comparableto sort a list ofPersonobjects by theirage:Output:
Comparator
Comparatoris an interface in Java used to define multiple ways of comparing objects of a class. It is used to create custom comparison logic separate from the class itself.Key Characteristics:
Comparatorinterface, each defining a different sorting sequence.compare(Object o1, Object o2).java.utilpackage.Usage Example: Here's how you can use
Comparatorto sort a list ofPersonobjects by theirnameandage:Output:
Summary of Differences
java.langjava.utilcompareTo(Object o)compare(Object o1, Object o2)ComparableComparatorimplementationWhen to Use
Comparablemakes sense if the class has a natural order.