What is the difference between compare()
and compareTo()
methods in Java? Do those methods give the same answer?
From JavaNotes:
a.compareTo(b)
:
Comparable interface : Compares values and returns an int which tells if the values compare less than, equal, or greater than.
If your class objects have a natural order, implement the Comparable<T>
interface and define this method. All Java classes that have a natural ordering implement Comparable<T>
- Example: String
, wrapper classes, BigInteger
compare(a, b)
:
Comparator interface : Compares values of two objects. This is implemented as part of the Comparator<T>
interface, and the typical use is to define one or more small utility classes that implement this, to pass to methods such as sort()
or for use by sorting data structures such as TreeMap
and TreeSet
. You might want to create a Comparator object for the following:
sort()
method.If your class objects have one natural sorting order, you may not need compare().
Summary from http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html
Comparable
A comparable object is capable of comparing itself with another object.
Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances.
Use case contexts:
Comparable interface
The equals method and ==
and !=
operators test for equality/inequality, but do not provide a way to test for relative values.
Some classes (eg, String and other classes with a natural ordering) implement the Comparable<T>
interface, which defines a compareTo()
method.
You will want to implement Comparable<T>
in your class if you want to use it with Collections.sort()
or Arrays.sort()
methods.
Defining a Comparator object
You can create Comparators to sort any arbitrary way for any class.
For example, the String
class defines the CASE_INSENSITIVE_ORDER
comparator.
The difference between the two approaches can be linked to the notion of:
Ordered Collection:
When a Collection is ordered, it means you can iterate in the collection in a specific (not-random) order (a Hashtable
is not ordered).
A Collection with a natural order is not just ordered, but sorted. Defining a natural order can be difficult! (as in natural String order).
Another difference, pointed out by HaveAGuess in the comments:
Comparable
is in the implementation and not visible from the interface, so when you sort you don't really know what is going to happen. Comparator
gives you reassurance that the ordering will be well defined.