Sub topic 1
Why Java needs a definition of order
Every sorting operation in Java rests on one question: given two objects, which one comes first? Numbers and strings have an answer built in. Your own classes do not. This chapter explains why, shows what breaks when no answer exists, and sets up the two mechanisms the rest of the tutorial covers: Comparable and Comparator.
Prerequisites
This chapter assumes you already know:
- How to write Java classes and interfaces, and how generics such as
List<String>work. - Lambda expressions and method references at a basic level.
- The core collections:
List,SetandMap, and how to add elements to them. - What
equalsandhashCodedo, and that they answer "are these two objects the same?"
You do not need to know Comparable or Comparator yet. This chapter introduces them by name only.
The problem: references have no built-in order
For primitive types, the language defines order. The expression 3 < 5 compiles because < is defined for numeric primitives. For objects, < does not exist. This line is a compile error:
Person a = new Person("Ana", 31);
Person b = new Person("Bo", 25);
boolean first = a < b; // does not compile: bad operand types for binary operator '<'The compiler does not guess that you meant "by age" or "by name". A Person has several fields, and any of them could be the sort key. The only code that knows what "smaller" means is code you write. The Comparable and Comparator interfaces are the places you put that code so that library methods can call it.
Equality is not order
equals and hashCode tell you whether two objects are the same. They cannot tell you which comes first. Knowing that Ana and Bo are different leaves open whether Ana should be listed before Bo.
Hash-based collections such as HashSet and HashMap need only equality. They place elements by hash code, so iteration order is unrelated to any meaningful ranking. Sorting, searching a sorted structure, and finding a minimum or maximum all need a ranking. A ranking answers three outcomes for any pair (a, b):
acomes beforeb.aandbare tied.acomes afterb.
A tie is not the same as equal. Two people of age 31 can tie when ordering by age, while equals still says they are different people. Later chapters return to this gap, because it affects TreeSet and TreeMap.
What happens when no order exists
If you ask a Java API to order objects that have no defined order, you get one of two failures. The type system catches some cases at compile time. The others surface at run time.
The first example uses List<Person> with Collections.sort(list). If Person does not implement Comparable, the call is rejected by the compiler, because the method signature requires the element type to be comparable to itself.
The second case is more dangerous. Some APIs accept Object or an unconstrained type, so the compiler cannot object. They check at run time and throw ClassCastException. The following program shows two such cases:
import java.util.Arrays;
import java.util.TreeSet;
public class NoOrderDemo {
static class Point {
final int x;
final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
Object[] points = { new Point(2, 1), new Point(1, 5) };
try {
Arrays.sort(points);
System.out.println("sorted");
} catch (ClassCastException e) {
System.out.println("Arrays.sort failed: " + e.getClass().getSimpleName());
}
TreeSet<Point> set = new TreeSet<>();
try {
set.add(new Point(1, 2));
System.out.println("added");
} catch (ClassCastException e) {
System.out.println("TreeSet.add failed: " + e.getClass().getSimpleName());
}
}
}The output is:
Arrays.sort failed: ClassCastException
TreeSet.add failed: ClassCastExceptionThe ClassCastException message says that Point cannot be cast to java.lang.Comparable. The library tried to treat your object as comparable and found it was not.
Edge cases in the failure
Two details explain why this error sometimes appears late or not at all.
- Sorting needs at least two elements to compare.
Arrays.sorton an array of onePointdoes not throw, because no comparison happens. The bug stays hidden until a second element arrives. TreeSet.addfails on the first element. Since Java 7,TreeMap.putcompares the first key with itself so that a missing order is reported immediately. ATreeSetof non-comparable objects therefore fails on the very firstadd, even when the set is empty.
A hidden failure that appears only when the data grows is a good reason to define order explicitly when you design a class, not when the first crash report arrives.
Types that already have an order
Many standard classes ship with a built-in ordering. Java calls this the natural ordering of the type.
| Type | Natural order |
|---|---|
| `Integer`, `Long`, `Double` and other number wrappers | Numeric value |
| `String` | Lexicographic by UTF-16 code unit, case-sensitive |
| `Character` | Numeric code unit value |
| `Boolean` | `false` before `true` |
| Enums | Order of declaration (by ordinal) |
| `LocalDate`, `LocalDateTime` | Chronological |
The string rule surprises many learners. Comparison is by character code, so every uppercase ASCII letter comes before every lowercase one:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StringOrderDemo {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("pear", "Zebra", "apple", "Banana"));
Collections.sort(words);
System.out.println(words); // [Banana, Zebra, apple, pear]
System.out.println("Z".compareTo("a") < 0); // true
System.out.println("apple".compareTo("apricot") < 0); // true
}
}Zebra sorts before apple because 'Z' is 90 and 'a' is 97. If you want a dictionary-style order that ignores case, the natural ordering does not provide it. You need a different ordering supplied from outside the type, which is the job of Comparator.
Floating-point edge cases
Orderings must give a definite answer for every pair, even for awkward values. The Double natural ordering treats the special values in a way that differs from the < and == operators:
public class DoubleOrderDemo {
public static void main(String[] args) {
System.out.println(0.0 == -0.0); // true
System.out.println(Double.compare(0.0, -0.0)); // 1
System.out.println(Double.NaN == Double.NaN); // false
System.out.println(Double.compare(Double.NaN, Double.NaN)); // 0
System.out.println(Double.compare(Double.NaN, Double.POSITIVE_INFINITY)); // 1
}
}With ==, NaN is not even equal to itself, which would make sorting impossible. Double.compare fixes this by treating -0.0 as less than 0.0 and NaN as greater than everything, including positive infinity. The lesson is that a sorting order has stricter requirements than a relational operator, and the next chapters spell those requirements out.
Two ways to supply an order
Java gives you two answers to "who decides the order?" Each one is an interface with a single comparison method.
Comparable<T>puts the order inside the class. The class implementscompareTo(T other), and that becomes the one natural ordering of its instances. Strings and numbers work this way.Comparator<T>puts the order in a separate object. Itscompare(T a, T b)method ranks two instances from outside the class. You can write as many comparators as you like for the same class, and you can use one even when you cannot edit the class.
Both return an int that is negative, zero or positive. That sign convention is the shared vocabulary of the whole API, and the chapter after next covers its rules in detail.
Who asks for an order
Several parts of the standard library depend on a ranking. When you call any of them, the library must find a comparison method, either one you pass in or one the elements carry.
| Operation | Needs an order because |
|---|---|
| `Collections.sort`, `List.sort`, `Arrays.sort` | It must decide the final sequence |
| `stream.sorted()`, `stream.min()`, `stream.max()` | It must rank elements to pick or arrange them |
| `Collections.min`, `Collections.max` | It must find the extreme element |
| `Collections.binarySearch` | It halves the range by asking which side the target lies on |
| `TreeSet`, `TreeMap` | They keep keys in sorted order and find keys by comparison |
| `PriorityQueue` | It keeps the smallest element at the head |
The lookup rule is the same everywhere. If you supply a Comparator, the library uses it. If you do not, it falls back to the elements' Comparable implementation. If neither exists, you get the compile error or the ClassCastException shown earlier.
Common errors at this stage
- Using
<or>on objects. These operators work only on numeric primitives. Use a comparison method instead. - Treating
equalsas ordering. A correctequalssays nothing about which element comes first. - Assuming strings sort alphabetically. They sort by code unit, so
"Zebra"precedes"apple". - Trusting a small test. A list with one element never calls the comparison, so a missing ordering can go unnoticed.
- Expecting
HashSetto be sorted. It is not. Only tree-based and priority-based structures use an ordering.
What comes next
The next chapter implements Comparable and shows how compareTo declares a natural order. After that, the rules every comparison must obey are stated, and the tutorial then moves to Comparator, lambdas, factory methods, null handling and the sorted collections.
Exercise
A teammate writes new TreeSet<Point>() and adds one Point that does not implement Comparable and passes no Comparator. The code runs in a test with a single element and then fails in production with more data. Which exception does the first add throw on a current Java version, and why might the teammate have expected it not to?
Show answer
It throws ClassCastException on the very first add, because TreeMap.put compares the key with itself to check that an ordering exists. The teammate probably assumed a comparison needs two elements, which is true for Arrays.sort on a one-element array but not for TreeSet.
Exercise
Given List<String> names = new ArrayList<>(List.of("mia", "Zoe", "adam")), what does Collections.sort(names) produce, and what does this show about the natural ordering of String?
Show answer
It produces [Zoe, adam, mia]. The natural ordering compares UTF-16 code units, so the uppercase Z (90) comes before the lowercase a (97). It is case-sensitive and is not a dictionary order.
Exercise
Why can 0.0 == -0.0 be true while Double.compare(0.0, -0.0) returns a positive number, and why does the library need the second behavior?
Show answer
The == operator follows numeric equality, which treats both zeros as equal. Double.compare defines a strict total ranking in which -0.0 is less than 0.0 and NaN is greater than every other value. Sorting needs a definite answer for every pair, and == would even say NaN is not equal to itself.