Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท java.lang

The Comparable interface

Reference for java.lang.Comparable: define a natural ordering with compareTo(), the consistency-with-equals rule, sorting, and common comparison mistakes.

java.lang.Comparable<T> gives a class a natural ordering. Its single method, compareTo(T other), returns a negative number, zero or a positive number when this comes before, equals, or comes after other. Sorting methods such as Collections.sort() and Arrays.sort(), and sorted collections such as TreeSet and TreeMap, use that ordering when you do not pass a Comparator.

String, the wrapper classes, BigDecimal, LocalDate, enums and many other JDK classes already implement Comparable. Implement it for your own type when there is one obvious, universal order. When there are several reasonable orders, write comparators instead.

Java
record Version(int major, int minor) implements Comparable<Version> {
    public int compareTo(Version other) {
        int byMajor = Integer.compare(major, other.major);
        return byMajor != 0 ? byMajor : Integer.compare(minor, other.minor);
    }
}

Try it

Java Making a class sortable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Ordering that disagrees with equals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public interface Comparable<T> {
    int compareTo(T o);
}
Name Description
o The object to compare with. Must not be null.

Returns: a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than o. Only the sign matters; the magnitude is unspecified (for String it is a character difference, for Integer it is -1, 0 or 1).

Throws: NullPointerException if o is null, and ClassCastException if the types cannot be compared.

Usage notes

  • The contract. sgn(a.compareTo(b)) == -sgn(b.compareTo(a)), the relation is transitive, and a.compareTo(b) == 0 implies the same sign for every other object c. Break it and sorting may throw IllegalArgumentException: Comparison method violates its general contract! or return nonsense.
  • Consistent with equals is recommended. If compareTo returns 0 for objects that are not equals, sorted collections treat them as duplicates (the second example) while hash-based ones do not.
  • Never subtract to compare. a - b overflows for large values. Use Integer.compare(a, b), Double.compare(a, b) and friends.
  • Handle several fields by comparing the most significant first and falling through only on ties, or use Comparator.comparing(...).thenComparing(...) as a static comparator.
  • Compare floating-point fields with Double.compare. It orders NaN and -0.0 consistently, while the < operator does not.
  • Null is not comparable. compareTo(null) throws; sorted collections reject null elements.
  • Only one natural order. If you need to sort by something else, pass a Comparator to sort(), TreeSet or TreeMap.