Java Language The compareTo and compare Methods


Example

The Comparable<T> interface requires one method:

public interface Comparable<T> {

    public int compareTo(T other);

}

And the Comparator<T> interface requires one method:

public interface Comparator<T> {

    public int compare(T t1, T t2);

}

These two methods do essentially the same thing, with one minor difference: compareTo compares this to other, whereas compare compares t1 to t2, not caring at all about this.

Aside from that difference, the two methods have similar requirements. Specifically (for compareTo), Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. Thus, for the comparison of a and b:

  • If a < b, a.compareTo(b) and compare(a,b) should return a negative integer, and b.compareTo(a) and compare(b,a) should return a positive integer
  • If a > b, a.compareTo(b) and compare(a,b) should return a positive integer, and b.compareTo(a) and compare(b,a) should return a negative integer
  • If a equals b for comparison, all comparisons should return 0.