Sub topic 14
Pitfalls: mutable keys, inconsistent comparators and iteration changes
This chapter assumes you know how an ordered map or sorted set works, what a comparator is, and how Java's TreeMap and TreeSet are used. Most bugs with these collections come from three causes: keys that change after insertion, comparators that disagree with what you mean by "equal", and changes made to a collection while you iterate over it.
Mutable keys
An ordered collection places each key by comparing it with the keys already stored. The collection does not re-check its own layout later. If a key changes in a way that alters its comparison result, the key is now in the wrong place, and the collection cannot tell.
import java.util.TreeSet;
public class MutableKey {
static class Task {
int priority;
Task(int priority) { this.priority = priority; }
public String toString() { return "P" + priority; }
}
public static void main(String[] args) {
TreeSet<Task> tasks = new TreeSet<>((a, b) -> Integer.compare(a.priority, b.priority));
Task a = new Task(1);
Task b = new Task(5);
Task c = new Task(9);
tasks.add(a);
tasks.add(b);
tasks.add(c);
c.priority = 0; // changed while stored in the set
System.out.println(tasks); // [P1, P5, P0]
System.out.println(tasks.contains(c)); // false
System.out.println(tasks.remove(c)); // false
}
}The set still holds c, and it prints it, but the tree believes c belongs at the right end. A search for priority 0 goes left and finds nothing. The entry is now unreachable by lookup and cannot be removed.
The fix is to remove the key, change it, and insert it again. Better, use immutable keys such as String, Integer or a record.
Inconsistent comparators
A comparator must behave like a real ordering:
- Antisymmetry: if
compare(a, b)is negative, thencompare(b, a)is positive. - Transitivity: if
a < bandb < c, thena < c. - Consistency: the same inputs always give the same result.
A common mistake is subtracting integers, as in (a, b) -> a - b. This overflows for large values, so Integer.MAX_VALUE and -1 compare in the wrong direction. Use Integer.compare(a, b) instead.
Another mistake is a comparator that checks only part of the data. A sorted set treats two elements as the same when the comparator returns 0. If you compare people only by age, the second person of the same age is silently dropped.
import java.util.TreeSet;
public class PartialComparator {
record Person(String name, int age) {}
public static void main(String[] args) {
TreeSet<Person> people = new TreeSet<>((a, b) -> Integer.compare(a.age(), b.age()));
people.add(new Person("Ana", 30));
people.add(new Person("Ben", 30));
System.out.println(people.size()); // 1
}
}To keep both, add a tie-breaker: compare by age, then by name.
Changing the collection during iteration
Iterators of TreeMap and TreeSet are fail-fast. If the collection is structurally modified after the iterator is created, by any means other than the iterator's own remove, the next call throws ConcurrentModificationException.
import java.util.Iterator;
import java.util.TreeSet;
public class IterationChange {
public static void main(String[] args) {
TreeSet<Integer> nums = new TreeSet<>();
for (int i = 1; i <= 6; i++) nums.add(i);
Iterator<Integer> it = nums.iterator();
while (it.hasNext()) {
if (it.next() % 2 == 0) it.remove(); // safe
}
System.out.println(nums); // [1, 3, 5]
}
}Calling nums.remove(...) inside that loop instead would fail. Views from subMap and headSet are live, so changes to the original show through them, and writes outside the view's range are rejected.
Exercise
A TreeMap uses a comparator that compares only the first letter of each string key. You call put("apple", 1) and then put("avocado", 2). What does the map contain, and how would you fix the comparator?
Show answer
The map holds one entry. The comparator returns 0 for the two keys, so the second put replaces the value of the existing entry. The key stays "apple" and the value becomes 2. To keep both entries, compare the whole string, or compare the first letter and then break ties with the full string.