javacomparecompareto

What is the difference between compare() and compareTo()?


What is the difference between compare() and compareTo() methods in Java? Do those methods give the same answer?


Solution

  • From JavaNotes:

    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: