Scrivio Interview library
ConceptIntermediate6 min read · updated 12 November 2026

What does it mean for compareTo to be consistent with equals, and what goes wrong in a TreeSet or TreeMap when it is not? Give a JDK example.

compareTo is consistent with equals when a.compareTo(b) == 0 exactly when a.equals(b) is true. Sorted collections such as TreeSet and TreeMap use only compareTo, or their comparator, to decide whether two elements are the same, so elements that compare as 0 are treated as duplicates even if equals says they differ. The JDK example is BigDecimal: new BigDecimal("1.0") and new BigDecimal("1.00") are not equal but compare as 0, so a HashSet holds both and a TreeSet holds one.

Why this question is asked

Most of the time, we assume a collection decides equality by calling equals. That is true for HashSet and HashMap, but not for the sorted collections, and the difference only matters when compareTo and equals disagree. When they do, the same data gives a different number of elements depending on which set we chose, and records silently disappear from sorted sets. Interviewers ask about this at this level because it combines two contracts and has a well-known JDK example. In this answer, we will define consistency with equals, see how TreeSet and TreeMap decide duplicates, walk through the BigDecimal example, look at the common one-field comparator bug, and see when inconsistency is intended and how to document it.

1What Consistent With equals Means

A class's natural ordering, defined by its compareTo method from Comparable, is consistent with equals if, for every pair of objects, a.compareTo(b) returns 0 exactly when a.equals(b) returns true. The same definition applies to a Comparator. The Comparable Javadoc strongly recommends consistency but does not require it, which is why inconsistent orderings exist in the JDK itself.

Notice that consistency is about the zero case only. The order of unequal elements is the comparator's business; what matters is that "compares as equal" and "is equal" mean the same thing.

2How Sorted Collections Decide Duplicates

A HashSet asks two questions about a new element: which bucket, using hashCode, and is there an equal element in it, using equals. A TreeSet works differently. It is a red-black tree, and to place an element it walks down the tree comparing the new element with existing ones. If any comparison returns 0, the TreeSet concludes the element is already present and does not add it. It never calls equals.

TreeMap does the same with keys. If put finds a key that compares as 0, it keeps the existing key object and replaces its value. The Javadoc describes this exactly: a sorted set's behaviour is well defined even when its ordering is inconsistent with equals, but it then fails to obey the general contract of Set, which is defined in terms of equals.

Which method decides duplicates
CollectionUses to find duplicatesEffect of inconsistency
HashSet, HashMaphashCode, then equalsFollows equals
TreeSet, TreeMapcompareTo or the comparatorElements that compare as 0 are merged
List.contains, indexOfequalsFollows equals
Collections.binarySearchcompareTo or the comparatorFinds an element that compares as 0
The same objects can be duplicates in one collection and distinct in another.

3The BigDecimal Example

BigDecimal stores a number as an unscaled value and a scale, the number of digits after the decimal point. 1.0 has scale 1 and 1.00 has scale 2. Its equals compares both the value and the scale, so they are not equal. Its compareTo compares only the numeric value, so they compare as 0.

Java
BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("1.00");
a.equals(b); // false: different scale
a.compareTo(b); // 0: same numeric value
Set<BigDecimal> hash = new HashSet<>(List.of(a, b));
hash.size(); // 2
Set<BigDecimal> tree = new TreeSet<>(List.of(a, b));
tree.size(); // 1
tree; // [1.0]: the first one added is kept
Map<BigDecimal, String> prices = new TreeMap<>();
prices.put(a, "first");
prices.put(b, "second");
prices; // {1.0=second}: key kept, value replaced

Both answers are defensible for a number. Treating 1.0 and 1.00 as different makes sense when the scale carries meaning, such as the precision of a measurement, and treating them as the same makes sense for arithmetic. The trouble comes when code switches between a HashSet and a TreeSet, or deduplicates prices with one and looks them up with the other. A common remedy is to normalise values before storing them, for example with stripTrailingZeros() or setScale to a fixed scale for money, so that equals and compareTo agree for the values we actually use.

4The One-Field Comparator Bug

The more frequent everyday version of this problem is a comparator that compares only one field, used for a TreeSet or a TreeMap.

Java
record Employee(long id, String name, int salary) {}
Set<Employee> bySalary = new TreeSet<>(Comparator.comparingInt(Employee::salary));
bySalary.add(new Employee(1, "Ana", 5000)); // true
bySalary.add(new Employee(2, "Bo", 5000)); // false: compares as 0 with Ana, silently dropped
bySalary.size(); // 1
Set<Employee> fixed = new TreeSet<>(Comparator.comparingInt(Employee::salary)
.thenComparingLong(Employee::id));
fixed.add(new Employee(1, "Ana", 5000));
fixed.add(new Employee(2, "Bo", 5000));
fixed.size(); // 2

Notice that add returns false, but nothing else signals the loss. A report built from bySalary would quietly miss every employee who shares a salary with someone already in the set. The fix is a tie-breaker on a unique field, such as the ID, so that the comparator returns 0 only for the same employee, which makes it consistent with the record's equals in practice.

5When Inconsistency Is Intended, and How to Document It

Sometimes treating different objects as the same is exactly what we want. String.CASE_INSENSITIVE_ORDER makes a TreeSet treat "Java" and "java" as one element, which is a simple way to build a case-insensitive set of names or headers. That is a deliberate choice, and it is safe as long as everyone using the set knows it.

So when an ordering is inconsistent with equals, we document it, as the BigDecimal Javadoc does with a note that its natural ordering is inconsistent with equals. For our own comparators, a short comment or a name such as CASE_INSENSITIVE_NAME_ORDER tells the next reader that a TreeSet built with it will merge elements. When the inconsistency is not intended, the fix is a unique tie-breaker.

6Follow-up questions

Does the inconsistency also affect sorting a list?

No. List.sort only needs a consistent order, and elements that compare as 0 simply keep their relative order because the sort is stable. Nothing is dropped. The danger is specific to collections that use the comparator to decide identity, such as TreeSet, TreeMap and binary search.

Is BigDecimal the only inconsistent class in the JDK?

It is the best-known one. Comparators such as String.CASE_INSENSITIVE_ORDER and Collator instances are also inconsistent with String.equals on purpose. In general, any comparator that ignores some of the fields equals uses is inconsistent, and is worth a comment.

How would you test for this?

For a Comparable class, a property-style test can generate pairs and assert that compareTo returns 0 if and only if equals returns true. For comparators used in sorted sets, a test that adds two distinct objects with equal sort keys and checks that both are kept catches the missing tie-breaker.

7Conclusion

In this answer, we saw that compareTo is consistent with equals when it returns 0 exactly for equal objects. TreeSet and TreeMap decide duplicates with compareTo or their comparator, never equals, so inconsistent orderings merge elements. BigDecimal 1.0 and 1.00 are not equal but compare as 0, so a HashSet keeps both and a TreeSet keeps one, and a comparator on a single field silently drops records with equal keys unless we add a unique tie-breaker. Intended inconsistency, such as case-insensitive ordering, should be documented.

What to say in the interviewAbout 70 seconds aloud

Open with

Consistent with equals means compareTo returns zero exactly when equals returns true. It matters because sorted collections like TreeSet and TreeMap never call equals: they walk the tree with compareTo or the comparator, and if any comparison returns zero they treat the new element as a duplicate.

Then, if they want more

A TreeSet then just does not add it, and a TreeMap keeps the existing key and replaces the value. The classic JDK example is BigDecimal. new BigDecimal("1.0") and new BigDecimal("1.00") are not equal, because equals compares the scale too, but compareTo compares only the numeric value and returns zero.

So a HashSet with both has size two and a TreeSet has size one. The everyday version of the bug is a comparator on one field, say salary, used for a TreeSet: the second employee with the same salary is silently dropped, and add just returns false.

The fix is a unique tie-breaker such as thenComparing by ID, or normalising values like BigDecimal to a fixed scale. Sometimes inconsistency is intended, like String.CASE_INSENSITIVE_ORDER for a case-insensitive set, and then it should be clearly documented, as BigDecimal's Javadoc does.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What does it mean for compareTo to be consistent with equals, and what goes wrong in a...": https://scrivio-interview-library.netlify.app/java/object-contracts/9a790fea88/