Object identity and equality contracts
What you will learn
Identity, logical equality and ordering answer different questions. Identity asks whether two references denote the same object; equality asks whether the represented values match; ordering decides which value comes before another. Choose a contract for each operation.
- Check identity and equality properties separately.
- Distinguish natural ordering from a supplied comparator.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed. List, Map and Set operations used here are brief previews of later collection chapters.
Check the equality contract across three values
public class Main { record Label(String text) {} public static void main(String[] args) { Label a = new Label("A"); Label b = new Label("A"); Label c = new Label("A"); System.out.println(a == b); System.out.println(a.equals(a) && a.equals(b) && b.equals(a)); System.out.println(a.equals(b) && b.equals(c) && a.equals(c)); System.out.println(a.equals(null)); System.out.println(a); }}Expected output:
falsetruetruefalseLabel[text=A]The generated record equality compares components. The final line is the observed JDK 21 diagnostic representation; do not parse it as a stable wire format.
Rules and mental model
The Comparable interface defines a type’s natural ordering; a Comparator supplies an independent ordering policy. A comparison returns a negative number, zero, or a positive number, not necessarily -1 or 1. Sorted sets and maps treat a comparison of zero as equivalence for their ordering, so an ordering that ignores identifying fields can collapse distinct values. Consistency with equals is generally desirable for those uses. A toString implementation should help diagnosis without exposing sensitive fields; it is not automatically a stable serialization format. Object.clone normally performs a shallow field copy if supported; prefer explicit copying when ownership matters. Finalization is deprecated for removal and is not reliable resource cleanup; use the resource patterns from Chapter 12. Do not infer identity from cached boxed values.
Choose natural order or a separate priority order
import java.util.*;public class Main { record Job(String id, int priority) implements Comparable<Job> { public int compareTo(Job other) { int byId = id.compareTo(other.id); return byId != 0 ? byId : Integer.compare(priority, other.priority); } } static final class PriorityOrder implements Comparator<Job> { public int compare(Job a, Job b) { return Integer.compare(a.priority(), b.priority()); } } public static void main(String[] args) { Job a = new Job("A", 2); Job b = new Job("B", 2); Comparator<Job> byPriority = new PriorityOrder(); System.out.println(a.compareTo(b) < 0); System.out.println(byPriority.compare(a, b)); System.out.println(a.equals(b)); }}Expected output:
true0falseNatural order includes both fields; the priority-only comparator intentionally ties different jobs. A sorted set using that comparator would not retain both as separate ordering keys.
Common mistakes
Do not subtract arbitrary int values to implement comparison: the subtraction can overflow. Use Integer.compare. Do not use == to compare boxed numbers by value.
Practice
Define a record Room(int floor, int number) with natural ordering by floor, then number. Compare rooms (1,9), (2,1) and another (1,9). Print whether the first precedes the second and whether the two equivalent rooms compare as zero.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Object identity and equality contracts — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
What does a.compareTo(b) < 0 mean?
What can happen in a sorted set using the priority-only comparator?
Why avoid subtracting arbitrary int priorities?