Quick revision
The short answer
TreeMap decides that two keys are the same only by comparing them, with compareTo for natural ordering or with the Comparator we supplied; it never calls equals() or hashCode(). If compare returns 0, the keys are treated as the same key, so put() replaces the value. A comparator that compares only part of the state, for example only the name, therefore merges distinct people who share a name, and the map breaks the general Map contract, which is defined in terms of equals(). The fix is to make the comparator consistent with equals by adding tie-breakers, such as Comparator.comparing(Person::name).thenComparing(Person::id).
What to remember
In this answer, we saw that TreeMap identifies keys only through compareTo or the supplied Comparator and never calls equals() or hashCode(). A comparison result of 0 means the same key, so put() replaces the value. A comparator that looks at only part of the state, such as the name, merges distinct objects that share it, makes containsKey() true for keys that do not exist and breaks the general Map contract defined by equals(). The fix is a comparator consistent with equals, built with tie-breakers such as Comparator.comparing(Person::name).thenComparing(Person::id).
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
TreeMap decides that two keys are the same only by comparing them, with compareTo for natural ordering or with the Comparator we supplied; it never calls equals() or hashCode(). If compare returns 0, the keys are treated as the same key, so put() replaces the value. A comparator that compares only part of the state, for example only the name, therefore merges distinct people who share a name, and the map breaks the general Map contract, which is defined in terms of equals(). The fix is to make the comparator consistent with equals by adding tie-breakers, such as Comparator.comparing(Person::name).thenComparing(Person::id).
Why this question is asked
TreeMap and TreeSet are the go-to collections when we need keys in sorted order, and they are usually introduced with a comparator written for sorting rather than for identity. That is where a quiet bug creeps in: entries disappear, sizes are smaller than expected, and a TreeSet and a HashSet built from the same data disagree. Interviewers ask this to check that we know how a sorted map finds keys and what consistent with equals means. In this answer, we will recap how TreeMap is organised, see how it decides two keys are the same, reproduce the problem with a name-only comparator, explain what contract it breaks, and fix it with tie-breakers.
1A Quick Recap: How TreeMap Is Organised
A TreeMap stores its entries in a red-black tree, a binary search tree that rebalances itself so its height stays logarithmic. Every node has a smaller side and a larger side. To find a key, the map starts at the root, compares the key with the node's key, and goes left if it is smaller, right if it is larger, until it finds a match or runs out of nodes. So get(), put() and remove() cost O(log n) comparisons.
The comparison comes either from the keys' natural ordering, their compareTo() method if they implement Comparable, or from a Comparator passed to the constructor. Nothing else is used: TreeMap never calls hashCode(), and it never calls equals() on keys.
2How TreeMap Decides Two Keys Are the Same
During the search, a comparison result of 0 means found. For put(), that means the key already exists, so TreeMap replaces the value of that node and keeps the original key object. For get() and containsKey(), it means a match, even if the object we passed is not equal() to the stored one.
- Start at the root
- compare(key, node.key)only the comparator, never
equals() - Result is 0?YesSame key: replace the value, keep the old keyNoGo left if negative, right if positive
- Reached an empty child?YesInsert a new node and rebalanceNoCompare with the next node
4 steps in order. Play them, or step through them one at a time.
Notice what happened to the two Anns. The second put() found the first Ann's node, because their names compare equal, and replaced the value. The map now says person 1 is a viewer, a role that belonged to person 2, and person 2 is gone. No exception, no warning. And containsKey() returns true for a person who does not exist, because only the name was compared.
3What Contract the Map Breaks
The Map interface defines its behaviour in terms of equals(): containsKey(k) is true if the map holds a key equal to k, and two different keys are two entries. TreeMap's Javadoc states that the ordering must be consistent with equals for the map to correctly implement the Map interface, meaning compare(a, b) == 0 exactly when a.equals(b). Our byName comparator returns 0 for two Person records that are not equal, so the map follows its comparator and quietly stops behaving like a Map.
The practical result is that the same data gives different answers in different collections.
| Keys added | HashMap (equals) | TreeMap by name | TreeMap by name, then id |
|---|---|---|---|
Person(1, Ann), Person(2, Ann) | 2 entries | 1 entry, value overwritten | 2 entries |
containsKey(Person(99, Ann)) | false | true | false |
BigDecimal 1.0 and 1.00 | 2 entries | 1 entry (natural order) | not applicable |
The JDK itself has a well-known example of an ordering that is not consistent with equals: BigDecimal. new BigDecimal("1.0") and new BigDecimal("1.00") compare as equal but are not equals(), because equals() also compares the scale. A HashSet holds both values, a TreeSet holds one.
4Fixing It With Tie-Breakers
The fix is to make the comparator decide ties using the rest of the identity, so that it returns 0 only for keys that are really equal. Comparator's thenComparing methods make this easy: the first comparison gives the order we want to see, and later ones only break ties.
Notice that the map is still sorted by name for display, with the two Anns ordered by id. Since Person is a record whose equals() compares id and name, and the comparator now compares both, the two agree: compare returns 0 exactly when equals returns true. If the key had more fields in equals(), the comparator would need to include them all, or the key type should be reduced to the fields that define identity.
5Follow-up questions
Is an inconsistent comparator ever acceptable?
Yes, when merging is exactly what we want and we document it. A TreeSet with String.CASE_INSENSITIVE_ORDER deliberately treats "Ann" and "ann" as one element, which is useful for a set of case-insensitive names. The problem is only when the merge is accidental. Even then, we should remember that such a collection does not follow the general Set or Map contract.
Does TreeMap allow a null key?
Not with natural ordering, because compareTo cannot be called on null and the map throws NullPointerException. With a comparator that handles null, such as Comparator.nullsFirst(...), a null key is allowed. Null values are always fine.
What happens if a key's compared fields change after insertion?
The node is now in the wrong place in the tree, so searches for it, and sometimes for other keys, go the wrong way and miss. Like hash keys, keys in a TreeMap must not change the fields their comparator uses while they are in the map.
6Conclusion
In this answer, we saw that TreeMap identifies keys only through compareTo or the supplied Comparator and never calls equals() or hashCode(). A comparison result of 0 means the same key, so put() replaces the value. A comparator that looks at only part of the state, such as the name, merges distinct objects that share it, makes containsKey() true for keys that do not exist and breaks the general Map contract defined by equals(). The fix is a comparator consistent with equals, built with tie-breakers such as Comparator.comparing(Person::name).thenComparing(Person::id).
Open with
TreeMap is a red-black tree, so it finds keys purely by comparison: it uses the keys' compareTo for natural ordering, or the Comparator I passed in, and it never calls equals or hashCode.
Then, if they want more
During a search, a result of zero means it found the key. So for put, compare returning zero means the key already exists and the value is replaced, while the original key object stays. The problem appears when the comparator only looks at part of the object's state.
If I sort people by name only and put two different Persons both called Ann, the second put finds the first Ann's node and overwrites its value, so one person silently disappears and the other gets the wrong role, and containsKey returns true for any Ann, even one that does not exist.
That breaks the Map contract, which is defined in terms of equals, and TreeMap's documentation says the ordering must be consistent with equals for the map to behave like a Map.
The same data then gives different results in a HashMap and a TreeMap; BigDecimal 1.0 and 1.00 is the JDK's own example, since they compare equal but are not equals. The fix is to add tie-breakers until the comparator only returns zero for truly equal keys, for example Comparator.comparing(Person::name).thenComparing(Person::id).
The map is still sorted by name for display, but two different people are two entries.
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.
- Official documentation
- java.util.HashMap, API documentation, The Collections Framework, overview
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 "How does TreeMap decide that two keys are the same, and what problem appears when the...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/c231d0b163/