Sub topic 11
Consistency with `equals`
This chapter assumes you know Java classes, generics, equals, hashCode, and the basic Comparable and Comparator APIs. The focus is how comparison interacts with equality, especially in sorted collections.
Two meanings of “the same”
Java has two related questions:
- Does this object have the same value as another object?
- Should this object come before, after, or at the same position as another object?
The equals method answers the first question. A compareTo method or Comparator answers the second.
A comparison returns zero when two objects have the same position in the ordering. Ideally, that should mean that equals also returns true.
The recommended relationship is:
x.compareTo(y) == 0 if and only if x.equals(y)For a Comparator, the equivalent rule is:
comparator.compare(x, y) == 0 if and only if x.equals(y)This relationship is called consistency with equals. It is strongly recommended, but Java does not require every ordering to follow it.
Why sorted collections care
A HashSet uses equals and hashCode to decide whether an element is already present. A TreeSet uses its ordering instead. If the ordering returns zero, the TreeSet treats the objects as duplicates.
The same rule applies to keys in a TreeMap. A new key whose comparison with an existing key returns zero replaces the existing value, even if the keys are not equal according to equals.
| Collection | Decides identity using | Effect of comparison returning zero |
|---|---|---|
| `HashSet` | `equals` and `hashCode` | Objects may remain separate if `equals` is false |
| `TreeSet` | `compareTo` or `Comparator` | The second object is treated as a duplicate |
| `TreeMap` | `compareTo` or `Comparator` | The value for the existing key is replaced |
The `BigDecimal` example
BigDecimal is a well-known exception. Its equals method considers scale, but its compareTo method considers numerical value.
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class DecimalSets {
public static void main(String[] args) {
BigDecimal onePointZero = new BigDecimal("1.0");
BigDecimal onePointZeroZero = new BigDecimal("1.00");
Set<BigDecimal> hashSet = new HashSet<BigDecimal>();
hashSet.add(onePointZero);
hashSet.add(onePointZeroZero);
Set<BigDecimal> treeSet = new TreeSet<BigDecimal>();
treeSet.add(onePointZero);
treeSet.add(onePointZeroZero);
System.out.println(onePointZero.equals(onePointZeroZero)); // false
System.out.println(onePointZero.compareTo(onePointZeroZero)); // 0
System.out.println(hashSet.size()); // 2
System.out.println(treeSet.size()); // 1
}
}The two values represent the same numerical amount, so compareTo returns zero. Their scales differ, so equals returns false. The result is valid Java behavior, but it can surprise users who move values between hash-based and sorted collections.
Designing your own types
For a class with a natural ordering, make the fields used by compareTo match the fields used by equals whenever possible. For a separate Comparator, decide what “same position” means before using it with a sorted collection.
If an ordering intentionally ignores a field, objects that differ only in that field may compare as equal. That can be useful for sorting a display, but dangerous for a TreeSet.
A PriorityQueue also uses comparison to choose its next element, but it does not use comparison to remove duplicates. Therefore, inconsistency with equals is mainly a uniqueness and key-lookup concern for TreeSet and TreeMap.
Checking an ordering
Test both methods when you create a value type. Include values that differ in every field and values that compare as equal. Also test the behavior of the ordering inside a TreeSet or TreeMap; that is where inconsistency becomes visible.
Exercise
A Comparator compares people by last name only. Two people have the same last name but different first names. What can happen if this Comparator is used by a TreeSet?
Show answer
The Comparator returns zero for the two people, so the TreeSet keeps only one of them even if their equals methods return false.