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 Pass Information From One JSP to Another JSP ?

What are the Java Collection Classes That Implement List Interfac ...

What is a Compile Time Constant in Java ?

What are the Differences Between Internal and External Iterator i ...

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