CKTIS / Java
Comparable.compareTo(): natural ordering in Java
Compare objects by their natural order. Read the sign of the result, distinguish an ordering tie from equals, and choose which object to keep when values tie.
Version: Java SE 21
Syntax
Java SE 21 — java.lang.Comparable<T>
Interface method: int compareTo(T other);
Call: int result = a.compareTo(b);
Implementation signature for MyType implements Comparable<MyType>: @Override public int compareTo(MyType other)
Generic bound for natural-order helpers: <T extends Comparable<? super T>>Comparable.compareTo() names the instance method int compareTo(T other) in java.lang.Comparable<T>. The call a.compareTo(b) takes one argument and compares a with b in their natural order. A result < 0 means a comes before b, == 0 means they tie, and > 0 means a comes after b. Do not assume the result is exactly -1 or 1. For an alternative ordering, use a Comparator<T> and call compare(a, b).
Swapping the operands must reverse the sign, the order must be transitive, and tied objects must give the same sign when compared with any third comparable object. In a class hierarchy, use shared ordering rules for base and derived instances if they can be compared with each other. For int fields, use Integer.compare(x, y), not x - y, which can overflow. A null argument causes NullPointerException; an argument whose type prevents comparison causes ClassCastException.
Consistency with equals is strongly recommended, not required: a.compareTo(b) == 0 and a.equals(b) should give the same boolean result. Document any departure from that rule. For example, BigDecimal values 2.00 and 2.0 tie in natural order, but equals returns false because their scales differ. A TreeSet without a comparator treats them as the same element.
The generic bound <T extends Comparable<? super T>> lets you compare values of type T even if T inherits Comparable for a supertype. When scanning for a minimum or maximum, replace the current choice only if the new element is strictly smaller (< 0) or larger (> 0), respectively, to keep the first element on a tie. For two arguments, a.compareTo(b) <= 0 selects a on a tie.
Before clamping a value to a range, check min.compareTo(max) <= 0. Return min below the range, max above it, and the original value otherwise, including when it ties with either bound.
Examples
import java.math.BigDecimal;
public class Main {
static <T extends Comparable<? super T>> T min(T a, T b) {
return a.compareTo(b) <= 0 ? a : b;
}
static <T extends Comparable<? super T>> T clamp(T value, T min, T max) {
if (min.compareTo(max) > 0) {
throw new IllegalArgumentException("min > max");
}
if (value.compareTo(min) < 0) return min;
if (value.compareTo(max) > 0) return max;
return value;
}
public static void main(String[] args) {
BigDecimal a = new BigDecimal("2.00");
BigDecimal b = new BigDecimal("2.0");
BigDecimal high = new BigDecimal("3");
System.out.println("a < high: " + (a.compareTo(high) < 0));
System.out.println("a compares equal to b: " + (a.compareTo(b) == 0));
System.out.println("a.equals(b): " + a.equals(b));
System.out.println("min: " + min(a, b));
System.out.println("clamp: " + clamp(new BigDecimal("4"), a, high));
}
}Result
a < high: true a compares equal to b: true a.equals(b): false min: 2.00 clamp: 3
`a` and `b` tie numerically but have different scales. `min(a, b)` keeps the first argument, so it prints `2.00`. `clamp` returns the upper bound `3` because `4` exceeds it.
Related lessons
- Java · Lesson 5 · Advanced · Version: 2
- Java · Lesson 11 · Advanced · Version: 2
- Java · Lesson 15 · Advanced · Version: 2
- Java · Lesson 48 · Basic · Version: 2
- Java · Lesson 5 · Intermediate · Version: 2