Sub topic 2
Comparable and compareTo
This chapter assumes you know Java classes, interfaces and generics, lambdas, the basics of List and the Collections framework, and how equals and hashCode work. It covers the Comparable interface, what compareTo must return, and how the JDK uses it. The full rules of the comparison contract and the details of writing a good compareTo get their own chapters.
What Comparable is
java.lang.Comparable<T> is an interface with one method:
public interface Comparable<T> {
int compareTo(T other);
}A class that implements it declares that its instances have a natural ordering. This is the single default way to put two objects of that class in sequence. Library code that needs to sort or rank objects asks the objects themselves how they compare, by calling compareTo.
The type parameter T is almost always the class itself, as in class Person implements Comparable<Person>. It means "a Person knows how to compare itself to another Person".
What the return value means
a.compareTo(b) compares the receiver a with the argument b and returns an int. Only the sign of the result matters.
| Result | Meaning |
|---|---|
| Negative | `a` comes before `b` |
| Zero | `a` and `b` are tied in the ordering |
| Positive | `a` comes after `b` |
Never depend on the exact number. String.compareTo returns a character difference or a length difference, while Integer.compare returns -1, 0 or 1. Both are valid. When you need a portable check, test the sign, as in a.compareTo(b) < 0, and never test == -1.
A result of zero means "tied in the ordering". It does not mean "the same object" or "equals returns true". That difference matters for sorted collections and is covered in a later chapter.
Types that are already Comparable
Many JDK classes implement Comparable, so you can sort them with no extra code:
| Type | Natural ordering |
|---|---|
| `String` | Lexicographic, comparing UTF-16 code units |
| `Integer`, `Long`, and the other numeric wrappers | Numeric order |
| `Boolean` | `false` before `true` |
| `Character` | By character value |
| `BigDecimal`, `BigInteger` | Numeric order |
| `LocalDate`, `LocalDateTime`, `Instant` | Chronological order |
| Enum types | The order in which the constants are declared |
The String ordering surprises people, because it is not alphabetical in the dictionary sense. It compares character codes, so every uppercase letter sorts before every lowercase letter:
public class StringOrderDemo {
public static void main(String[] args) {
System.out.println(Integer.signum("apple".compareTo("banana"))); // -1
System.out.println(Integer.signum("Zebra".compareTo("apple"))); // -1, 'Z' is 90 and 'a' is 97
System.out.println(Integer.signum("app".compareTo("apple"))); // -1, a prefix sorts first
System.out.println("same".compareTo("same")); // 0
}
}Numeric types have a similar trap. Double.compareTo and Double.compare do not behave like < and == on primitive doubles. They place -0.0 before 0.0, and they treat NaN as equal to itself and greater than every other value. This gives a consistent total order, which sorting needs.
A class with a natural ordering
The Person class below orders people by age. It is the example used through the rest of this tutorial.
public class Person implements Comparable<Person> {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
@Override
public int compareTo(Person other) {
return Integer.compare(age, other.age);
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}Integer.compare(x, y) returns a negative number when x < y, zero when they are equal, and a positive number when x > y. The compareTo method delegates to it. Because compareTo is declared inside Person, it can read the private age field of other.
The next program (put it in the same package) calls compareTo directly and then sorts a list:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ComparableDemo {
public static void main(String[] args) {
Person ana = new Person("Ana", 31);
Person bo = new Person("Bo", 25);
Person cy = new Person("Cy", 31);
System.out.println(ana.compareTo(bo)); // 1, Ana is older so she comes after Bo
System.out.println(bo.compareTo(ana)); // -1
System.out.println(ana.compareTo(cy)); // 0, same age, so tied
List<Person> people = new ArrayList<>(List.of(ana, bo, cy));
Collections.sort(people);
System.out.println(people); // [Bo (25), Ana (31), Cy (31)]
}
}Ana and Cy are tied because only age takes part in the comparison. Collections.sort is stable, so tied elements keep their original relative order. Ana stays ahead of Cy because she was ahead of Cy in the input.
How library code uses compareTo
Sorting code never needs to know what a Person is. It only needs to call compareTo. The sequence below shows what happens inside Collections.sort(people).
These JDK features all rely on the natural ordering of the element type:
Collections.sort(list)andArrays.sort(array)Collections.minandCollections.maxcalled without a comparatorStream.sorted()with no argumentsTreeSet,TreeMapandPriorityQueuecreated without a comparatorComparator.naturalOrder()andComparator.reverseOrder()
The next chapters cover the APIs one by one. The point here is that implementing Comparable once makes your class work with all of them.
When a class is not Comparable
The compiler protects you in some places and the runtime does in others. The signature of the one-argument sort is:
public static <T extends Comparable<? super T>> void sort(List<T> list)If T does not implement Comparable, Collections.sort(list) does not compile. The ? super T part allows a subclass to be sorted when its superclass implements Comparable. For example, class Student extends Person can be sorted with the ordering inherited from Person.
Collections that sort as you insert are less strict at compile time. Their element type has no bound, so a missing Comparable shows up as an exception:
import java.util.TreeSet;
public class NotComparableDemo {
static class Box { }
public static void main(String[] args) {
TreeSet<Box> boxes = new TreeSet<>();
boxes.add(new Box()); // throws ClassCastException: Box cannot be cast to Comparable
}
}The failure happens on the first add, even when the set is empty, because TreeMap compares the key with itself to check its type. If you see a ClassCastException that mentions Comparable, either the element class needs to implement it or the collection needs a Comparator.
Null and mixed types
By convention, compareTo(null) throws NullPointerException. It must not return a number, because null is not an instance of any class and e.equals(null) returning false does not carry over to ordering. The JDK classes follow this:
public class NullCompareDemo {
public static void main(String[] args) {
String s = "abc";
s.compareTo(null); // throws NullPointerException
}
}Your own implementations get this behavior for free when they dereference the argument, as Person.compareTo does with other.age. Sorting a list that contains null with natural ordering fails for this reason. Ordering null values on purpose is handled by comparator wrappers, which a later chapter covers.
Always implement Comparable<Person> and not the raw type Comparable. With the raw type, the method becomes compareTo(Object). The compiler no longer checks the argument type, and passing the wrong type fails at runtime with a ClassCastException.
Common mistakes at this stage
- Forgetting the type argument.
implements Comparablecompiles with a warning, but you must then writecompareTo(Object o)and cast. - Checking for -1 or 1. Only the sign is guaranteed. Use
< 0,== 0and> 0. - Comparing with
<on boxed numbers or==on strings. UsecompareToor thecomparestatic methods. - Using subtraction to compare numbers.
age - other.agelooks equivalent toInteger.compare, but it overflows for large values and gives the wrong sign. The pitfalls chapter shows a concrete case. UseInteger.compare,Long.compareorDouble.compare. - Ordering by a field that changes. If an object sits in a
TreeSetorTreeMapand its compared field changes, the collection can no longer find it. Prefer immutable fields incompareTo, asPersondoes withfinal. - Assuming a tie means equal.
compareToreturning0andequalsreturningtrueare separate questions. Keep them aligned when you can.
Summary of the working model
Comparable<T>has one method,int compareTo(T other), and defines the class's natural ordering.- Negative means "this comes first", zero means "tied", positive means "this comes after".
- JDK sorting and sorted collections call
compareTowhen you give them no comparator. compareTo(null)should throwNullPointerException.- A missing
Comparableis a compile error forCollections.sort, and aClassCastExceptionat run time forTreeSet,TreeMapandPriorityQueue.
Exercise
A class Version has a private final int major field and implements Comparable<Version>. A colleague wrote public int compareTo(Version other) { return major > other.major ? 1 : 0; }. Give one example where this breaks sorting, and write a corrected one-line body.
Show answer
It never returns a negative number. For a = Version(1) and b = Version(2), a.compareTo(b) returns 0, which says they are tied. Sorting cannot place a before b, so the result depends on the input order. Also, b.compareTo(a) returns 1 while a.compareTo(b) is 0, so the two directions disagree. The corrected body is return Integer.compare(major, other.major);.
Exercise
What happens when you run new TreeSet<Object>().add(new Object()), and what happens with List<Object> list = new ArrayList<>(); Collections.sort(list);? Explain the difference.
Show answer
The TreeSet call compiles and then throws ClassCastException at run time, because Object is not Comparable and the set has no comparator. The Collections.sort(list) call does not compile. The method requires T extends Comparable<? super T>, and Object does not meet that bound. The TreeSet element type has no such bound, so the error is found only at run time.