Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Comparable — natural ordering of objects

java.lang.Comparable<T> defines objects' natural ordering through compareTo(T o). Its result indicates order, not the distance between values.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public interface Comparable<T> {
    int compareTo(T o);
}

java.lang.Comparable<T> defines a natural total ordering. Comparable.compareTo, declared as int compareTo(T o), returns a negative value, zero, or a positive value when this object is respectively less than, equivalent in ordering to, or greater than the argument. The sign matters, not exactly -1 or 1.

The contract requires opposite signs when arguments are reversed, transitivity, and identical comparison signs against every third object for objects comparing as zero. An exception in one direction requires an exception in the reverse direction too.

Consistency of compareTo == 0 with equals is strongly recommended; document deviations. Without it, a sorted set can reject an unequal object as a duplicate. compareTo(null) throws NullPointerException; an incompatible type can cause ClassCastException.

The example sorts Score using Arrays.sort. Using Integer.compare instead of subtraction avoids overflow; the record's single field makes its ordering consistent with equals.

Examples

import java.util.Arrays;

public class Main {
    record Score(int points) implements Comparable<Score> {
        @Override
        public int compareTo(Score other) {
            return Integer.compare(points, other.points);
        }
    }

    public static void main(String[] args) {
        Score[] scores = {new Score(30), new Score(10), new Score(20)};
        Arrays.sort(scores);
        for (Score score : scores) {
            System.out.println(score.points());
        }
    }
}

Result

10
20
30

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources