What are the Differences Between Comparable and Comparator in Java ?

Main differences between Comparable and Comparator are...

Type - Comparable is an interface in Java where T is the type of objects that this object may be compared to.

Comparator is also an interface where T is the type of objects that may be compared by this comparator.

Sorting - In Comparable, we can only create one sort sequence. In Comparator we can create multiple sort sequences.

Method Used - Comparator interface in Java has method public int compare (Object o1, Object o2) that returns a negative integer, zero, or a positive integer when the object o1 is less than, equal to, or greater than the object o2. A Comparable interface has method public int compareTo(Object o) that returns a negative integer, zero, or a positive integer when this object is less than, equal to, or greater than the object o.

Objects for Comparison - The Comparator compares two objects given to it as input. Comparable interface compares "this" reference with the object given as input.

Package location - Comparable interface in Java is defined in java.lang package. Comparator interface in Java is defined in java.util package.



You May Interest

How Will You Define the Scope of a Bean in Spring ?

What is the Reason For Overriding equals Method in Java ?

Why Collection Interface Doesn’t Extend Cloneable and Serializabl ...

How Strategy Design Pattern is Different From State Design Patter ...

What is the Lifecycle Stages of JSP ?