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

What are the Different Scopes of a JSP Object ?

When is UnsupportedOperationException Thrown in Java ?

Why Java Provides Garbage Collector ?

What is String Interning in Java ?

What is Volatile Keyword in Java ?