Sub topic 4
Giving Your Class a Natural Ordering
This chapter assumes you know Java classes, interfaces and generics, and that you have met equals and hashCode. It also assumes you can read a lambda or method reference. The goal is to make your own class sortable by default, so that Collections.sort(list), TreeSet and PriorityQueue work on it without extra arguments.
What a natural ordering is
A class has a natural ordering when it implements Comparable<T>. The interface has one method:
public interface Comparable<T> {
int compareTo(T other);
}a.compareTo(b) returns a negative number if a sorts before b, zero if they sort as equal, and a positive number if a sorts after b. Only the sign matters. The method can return -1, -57 or Integer.MIN_VALUE for "before".
The word "natural" signals that the class has exactly one built-in order. String sorts alphabetically by UTF-16 code units. Integer sorts numerically. LocalDate sorts chronologically. Library code such as Collections.sort(List<T>), Arrays.sort(Object[]), TreeSet and TreeMap falls back on this order when you give it no Comparator.
A first implementation
Here is Person ordered by age, as a starting point:
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 + ")";
}
}Three details matter here.
- The type argument.
Comparable<Person>makes the parameter ofcompareToaPerson. If you write the raw typeComparable, the parameter becomesObject. You then need a cast, and a wrong type fails at run time withClassCastExceptioninstead of at compile time. Integer.compare. It returns a negative number, zero or a positive number without overflow. The pitfalls chapter explains whyage - other.ageis unsafe.- Access to private fields.
other.agecompiles becausecompareTois insidePerson, and private access is per class, not per object.
The rules your compareTo must follow
The Comparable documentation sets a contract. Sorting algorithms rely on it, and they can throw IllegalArgumentException("Comparison method violates its general contract!") or return a wrongly ordered result when it is broken.
- Antisymmetry.
sgn(a.compareTo(b)) == -sgn(b.compareTo(a))for allaandb. Ifais beforeb, thenbis aftera. - Transitivity. If
a.compareTo(b) > 0andb.compareTo(c) > 0, thena.compareTo(c) > 0. - Substitutivity of ties. If
a.compareTo(b) == 0, thenaandbcompare the same way against every other objectc. - Null.
a.compareTo(null)should throwNullPointerException. It should not return a number. - Consistency with equals (strongly recommended).
a.compareTo(b) == 0should hold exactly whena.equals(b)is true.
The first three rules describe a mathematical total preorder. The last two are about how your class behaves at the edges, and the next two sections cover them.
The tie problem
The Person above compares only by age. In this program Ana and Cy, both 31, compare as equal:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class TieDemo {
public static void main(String[] args) {
List<Person> people = new ArrayList<>(List.of(
new Person("Ana", 31), new Person("Bo", 25), new Person("Cy", 31)));
Collections.sort(people);
System.out.println(people); // [Bo (25), Ana (31), Cy (31)]
Set<Person> set = new TreeSet<>(people);
System.out.println(set.size()); // 2, not 3
}
}The list sort is fine. Collections.sort is stable, so equal elements keep their original relative order. The TreeSet is the problem. A TreeSet decides whether two elements are duplicates by asking whether compareTo returns 0. It never calls equals. Cy is therefore silently dropped as a duplicate of Ana.
This is the main reason to think about which fields a natural ordering uses. A natural ordering should rank objects so that "tied" means "the same value".
Comparing several fields
When the first field ties, move to the next field. Return the first non-zero result:
import java.util.Objects;
public final class Person implements Comparable<Person> {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = Objects.requireNonNull(name, "name");
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
@Override
public int compareTo(Person other) {
int byAge = Integer.compare(age, other.age);
if (byAge != 0) {
return byAge;
}
return name.compareTo(other.name);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
Person p = (Person) o;
return age == p.age && name.equals(p.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}Now Ana (31) sorts before Cy (31), and the TreeSet keeps all three people. compareTo and equals use the same two fields, so they agree. The class is final and the fields are immutable, which keeps both methods stable (see below).
name.compareTo(other.name) uses String's own natural ordering. It compares by character code, so "Z" sorts before "a". For human-friendly text ordering you would pass a Collator or a case-insensitive comparator from outside the class, which is the subject of the next chapter.
The same logic with a comparator constant
A compact alternative is to build the comparison once with the Comparator factory methods and delegate to it:
import java.util.Comparator;
public final class Person implements Comparable<Person> {
private static final Comparator<Person> NATURAL =
Comparator.comparingInt(Person::getAge)
.thenComparing(Person::getName);
// fields, constructor, getters, equals, hashCode, toString as above
@Override
public int compareTo(Person other) {
return NATURAL.compare(this, other);
}
}This is shorter and harder to get wrong when you have three or four fields. It allocates a few small objects once, and each call goes through a couple of extra method calls. In hot sorting loops over very large data, the hand-written version can be slightly faster. Pick one style per codebase.
Comparing fields of different types
Use the matching comparison method for each field type:
| Field type | Use |
|---|---|
| `int`, `long`, `short`, `char`, `byte` | `Integer.compare`, `Long.compare`, `Short.compare`, `Character.compare`, `Byte.compare` |
| `double`, `float` | `Double.compare`, `Float.compare` (they order `NaN` and `-0.0` consistently) |
| `boolean` | `Boolean.compare` (`false` before `true`) |
| `String`, `BigDecimal`, `LocalDate`, other `Comparable` objects | the field's own `compareTo` |
| Enum | `compareTo`, which orders by declaration position |
| Nullable field | decide the null rule yourself, or avoid null in this class |
For doubles, avoid a < b ? -1 : a > b ? 1 : 0. It treats NaN as equal to everything and breaks transitivity. Double.compare handles that case.
Fields that can be null
compareTo(null) should throw NullPointerException, and in the examples above it does, because other.age dereferences other. A field inside the object is a separate question. If name could be null, name.compareTo(...) would throw. Two simple choices are:
- Reject null in the constructor, as
Persondoes withObjects.requireNonNull. The ordering code stays simple. - Allow null and wrap the field comparator with
Comparator.nullsFirstornullsLast, then delegate as in the constant above.
Do not return an arbitrary value such as 0 whenever something is null. That breaks transitivity.
Where the ordering fits in a design
The ClassCastException branch is a common surprise. Collections.sort(List<Person>) will not compile if Person is not Comparable, because of its generic bound. A TreeSet<Person> or PriorityQueue<Person> compiles either way and fails only when the second element is added.
Design guidelines and edge cases
- Make the ordering part of the class's meaning. If there is no single obvious order (people by age, by name, by salary?), do not implement
Comparable. Provide namedComparatorconstants instead. - Keep the fields immutable. If an object sits in a
TreeSetorTreeMapand a field used incompareTochanges, the tree is not re-sorted. Lookups and removals then fail silently. - Inheritance is awkward. A subclass cannot implement
Comparable<Student>when its superclass already implementsComparable<Person>, because one class cannot implement the same generic interface with two arguments. Either make the superclass ordering general enough, or usefinalclasses and comparators. - Prefer
finalclasses or records for value types. A subclass that adds a field and extendscompareToeasily violates antisymmetry. - Prefer consistency with equals. Include in
compareToevery field thatequalsuses. If you deliberately do not, asBigDecimaldoes, write that in the Javadoc. - Return values are signs. Compare the result with
< 0,== 0and> 0, never with== -1or== 1.
Common errors at a glance
| Symptom | Likely cause |
|---|---|
| `TreeSet` or `TreeMap` has fewer entries than expected | `compareTo` returns 0 for objects you consider different, such as a missing tie-break field |
| `ClassCastException: ... cannot be cast to java.lang.Comparable` | The class does not implement `Comparable` and no `Comparator` was given |
| `IllegalArgumentException: Comparison method violates its general contract!` | Antisymmetry or transitivity is broken, often by subtraction overflow or a `NaN` mishandled by hand |
| `NullPointerException` inside a sort | A null element or null field with no null rule |
| Element cannot be found or removed from a `TreeMap` after a change | A field used by `compareTo` was mutated while the object was a key |
Exercise
Using the first, age-only version of Person, you add new Person("Ana", 31) and new Person("Cy", 31) to a TreeSet<Person>. How many elements does the set contain, and why? What is the smallest change to compareTo that fixes it?
Show answer
The set contains one of the two people, Ana, because Cy is added second and Ana is already present. TreeSet treats two elements as duplicates when compareTo returns 0, and Integer.compare(31, 31) is 0, so Cy is rejected. The fix is to break ties with another field: if the ages are equal, return name.compareTo(other.name). Then compareTo returns 0 only for the same name and age, which matches equals.
Exercise
A Version class has int fields major and minor. Write the body of compareTo so that 1.9 sorts before 1.10 and 2.0 sorts after both. Why would return major 100 + minor - (other.major 100 + other.minor) be a poor choice?
Show answer
Compare major first and return that result if it is not 0, then compare minor: int c = Integer.compare(major, other.major); if (c != 0) return c; return Integer.compare(minor, other.minor); The arithmetic version assumes minor is below 100, so it breaks for 1.150 versus 2.0. It also risks int overflow for large values, and it is harder to read than two Integer.compare calls.