Explain the difference between Comparator and Comparable in Java.
Explain the difference between Comparator and Comparable in Java.
797
18-Jul-2024
Ravi Vishwakarma
19-Jul-2024Comparator
andComparable
are 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
Comparable
is an interface in Java used to define the natural ordering of objects of a class. A class that implements theComparable
interface needs to override thecompareTo
method to specify how objects of that class should be compared.Key Characteristics:
compareTo
method, defining a single sorting sequence.compareTo(Object o)
.java.lang
package.Usage Example: Here's how you can use
Comparable
to sort a list ofPerson
objects by theirage
:Output:
Comparator
Comparator
is 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:
Comparator
interface, each defining a different sorting sequence.compare(Object o1, Object o2)
.java.util
package.Usage Example: Here's how you can use
Comparator
to sort a list ofPerson
objects by theirname
andage
:Output:
Summary of Differences
java.lang
java.util
compareTo(Object o)
compare(Object o1, Object o2)
Comparable
Comparator
implementationWhen to Use
Comparable
makes sense if the class has a natural order.