Sub topic 11
Consistency with equals
This chapter assumes you can write a Comparable class and a Comparator, and that you know the equals and hashCode contract. It covers a rule that is easy to miss: ordering and equality are two separate definitions of "the same", and some collections use one while others use the other.
Two definitions of "same"
Java has two ways to ask whether two objects are the same:
a.equals(b)asks whether they are equal.HashSet,HashMap,List.contains,List.remove(Object)andStream.distinct()use it.a.compareTo(b) == 0, orcomparator.compare(a, b) == 0, asks whether they tie in the ordering.TreeSet,TreeMapandCollections.binarySearchuse it.
An ordering is consistent with equals when, for every pair of elements, compare(a, b) == 0 has the same truth value as a.equals(b). When the two disagree, the ordering is inconsistent with equals.
The Comparable Javadoc says consistency is "strongly recommended" but not required. Your code compiles and sorts correctly either way. Trouble starts when you put such objects into a sorted collection.
A JDK example: BigDecimal
BigDecimal has a value and a scale (the number of digits after the decimal point). equals compares both, so 1.0 and 1.00 are different. compareTo compares only the numeric value, so they tie.
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class ScaleDemo {
public static void main(String[] args) {
BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("1.00");
System.out.println(a.equals(b)); // false
System.out.println(a.compareTo(b)); // 0
Set<BigDecimal> hash = new HashSet<>(Set.of(a, b));
Set<BigDecimal> tree = new TreeSet<>(Set.of(a, b));
System.out.println(hash.size()); // 2, because equals sees different scales
System.out.println(tree.size()); // 1, because compareTo returns 0
}
}Both sets were given the same two objects and ended up with different contents. Nothing here is a bug in the JDK. BigDecimal documents the inconsistency, and a TreeSet follows the ordering it is given.
How a TreeSet decides on duplicates
A TreeSet never calls equals on its elements. On add, it walks down a balanced tree and calls compare at each node. If any call returns 0, the tree decides the element is already present and does not insert it.
The diagram below shows the decision for a single add.
The consequence is that for a sorted set, the comparator is the definition of equality. Any two elements that tie are the same element, whatever equals says.
An inconsistency you can create by accident
The Person example from earlier chapters orders by age only. Here is a version as a record, so equals and hashCode come from both fields:
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class AgeOnlyDemo {
record Person(String name, int age) implements Comparable<Person> {
@Override
public int compareTo(Person other) {
return Integer.compare(age, other.age);
}
}
public static void main(String[] args) {
Person ana = new Person("Ana", 31);
Person cy = new Person("Cy", 31);
Set<Person> hash = new HashSet<>();
Set<Person> tree = new TreeSet<>();
for (Person p : new Person[] {ana, cy}) {
hash.add(p);
tree.add(p);
}
System.out.println(hash.size()); // 2
System.out.println(tree.size()); // 1, Cy was silently dropped
System.out.println(tree.contains(new Person("Zed", 31))); // true
}
}add returns false for Cy, but code that ignores the return value loses data without any error. contains answers true for a person who was never added, because Zed ties with Ana.
The sort itself is fine. Collections.sort on a list of these people keeps all of them, because sorting never discards ties. The damage appears only in collections that treat a tie as "the same element".
The fix: add tie-breakers
Make the ordering distinguish every pair that equals distinguishes. Compare the fields that equals uses, after your primary key:
@Override
public int compareTo(Person other) {
int byAge = Integer.compare(age, other.age);
if (byAge != 0) {
return byAge;
}
return name.compareTo(other.name);
}With a comparator, the same idea is a thenComparing chain:
Comparator<Person> consistent =
Comparator.comparingInt(Person::age)
.thenComparing(Person::name);Now compare(a, b) == 0 only when both age and name match, which is exactly when the record's equals returns true.
Comparators passed to a sorted collection
A Comparator supplied to new TreeSet<>(comparator) or new TreeMap<>(comparator) has the same effect. The collection uses it in place of equals for every operation.
import java.util.Map;
import java.util.TreeMap;
public class CaseInsensitiveDemo {
public static void main(String[] args) {
Map<String, Integer> counts = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
counts.put("Apple", 1);
counts.put("apple", 2);
System.out.println(counts); // {Apple=2}
System.out.println(counts.get("APPLE")); // 2
System.out.println(counts.size()); // 1
}
}The second put finds a tie, so it replaces the value and keeps the original key object "Apple". This behavior is useful when you want it, for example a case-insensitive lookup table. It is a hazard when you did not intend it, so a comparator that ties on non-equal elements should be a deliberate choice.
The Set and Map interfaces are specified in terms of equals. The TreeSet and TreeMap Javadoc says that with an inconsistent ordering the collection is still well-behaved, but it no longer obeys the general contract of Set or Map.
Where each API stands
| API | Uses for "same element" |
|---|---|
| `HashSet`, `HashMap` | `hashCode` and `equals` |
| `TreeSet`, `TreeMap` | `compareTo` or `compare` returning 0 |
| `List.contains`, `List.indexOf`, `List.remove(Object)` | `equals` |
| `Collections.binarySearch` | `compareTo` or `compare` |
| `PriorityQueue.offer`, `poll`, `peek` | ordering, for position in the heap |
| `PriorityQueue.contains`, `remove(Object)` | `equals` |
| `List.sort`, `Arrays.sort`, `Stream.sorted()` | ordering, and ties are kept |
| `Stream.distinct()` | `equals` |
A PriorityQueue mixes both. Ties between elements are allowed and kept, and they come out in no guaranteed order. contains and remove(Object) scan the queue using equals, so an inconsistent ordering does not lose elements there. It can still surprise you if you assume that "tied" means "removed together".
Rules of thumb
- If the class defines
equals, makecompareToreturn0only whenequalsreturnstrue. Use the same fields, or tie-break on all of them. - If
equalsis based on a unique id, finish your comparator chain with the id. The result is a total ordering with no accidental ties. - For the other direction, the contract is firm. If
a.equals(b)istrue, thena.compareTo(b)must be0. Breaking this makes sorted collections miss elements that are present. - If a class is deliberately inconsistent, document it, as
BigDecimaldoes. Callers who put it in aTreeSetthen know what to expect. - Prefer a separate
Comparatorfor orderings that intentionally collapse distinct objects, such as case-insensitive or by-department-only. Leave the class's natural ordering consistent.
Checking consistency in a test
A quick test catches most inconsistencies. For a representative set of values, check both directions for every pair:
import java.util.Comparator;
import java.util.List;
public class ConsistencyCheck {
record Person(String name, int age) {}
static <T> boolean consistentWithEquals(List<T> samples, Comparator<? super T> cmp) {
for (T a : samples) {
for (T b : samples) {
if ((cmp.compare(a, b) == 0) != a.equals(b)) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
List<Person> samples = List.of(
new Person("Ana", 31), new Person("Cy", 31), new Person("Bo", 25));
Comparator<Person> ageOnly = Comparator.comparingInt(Person::age);
Comparator<Person> ageThenName = ageOnly.thenComparing(Person::name);
System.out.println(consistentWithEquals(samples, ageOnly)); // false
System.out.println(consistentWithEquals(samples, ageThenName)); // true
}
}Include tie cases in the samples, such as two people with the same age. A sample with all-distinct values cannot reveal the problem.
Exercise
A TreeSet<Person> uses Comparator.comparing(Person::getName), and Person.equals compares name and age. You add new Person("Ana", 31) and then new Person("Ana", 40). What are the size of the set and the return value of the second add, and why? What would you change if you want both people kept?
Show answer
The size is 1 and the second add returns false. The comparator returns 0 for the two people because their names match, so the TreeSet treats the second as a duplicate even though equals says they differ. To keep both, add a tie-breaker so the comparator only returns 0 when equals would be true: Comparator.comparing(Person::getName).thenComparingInt(Person::getAge).
Exercise
A class has equals based on a unique long id, and a natural ordering by a score field only. A teammate sorts a List with it and sees no problem, then switches to a TreeSet and some objects vanish. Explain why the list worked, and write the compareTo ending that fixes it.
Show answer
Sorting keeps tied elements, so the list lost nothing. A TreeSet treats compareTo == 0 as a duplicate, so objects with the same score were dropped. Fix it by breaking ties on the id, for example: int c = Double.compare(score, other.score); return c != 0 ? c : Long.compare(id, other.id);