Quick revision
The short answer
It prints [abc, hello]. The comparator compares only string length, and a TreeSet decides that two elements are duplicates when compare returns 0, not when equals returns true. "xyz" has the same length as "abc", so the set treats it as a duplicate, add returns false and it is never stored. Adding a tie-breaker, Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()), fixes it; without one, the comparator is inconsistent with equals and the set violates the general Set contract.
What to remember
In this answer, we saw that the code prints [abc, hello] because TreeSet decides duplicates with compare, not equals, and the comparator considers strings of equal length to be the same, so add("xyz") returns false and contains("xyz") even returns true. A tie-breaker with thenComparing(Comparator.naturalOrder()) makes the comparator consistent with equals and keeps all three strings. An inconsistent comparator makes a sorted set violate the Set contract and silently drop data.
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.
It prints [abc, hello]. The comparator compares only string length, and a TreeSet decides that two elements are duplicates when compare returns 0, not when equals returns true. "xyz" has the same length as "abc", so the set treats it as a duplicate, add returns false and it is never stored. Adding a tie-breaker, Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()), fixes it; without one, the comparator is inconsistent with equals and the set violates the general Set contract.
Why this question is asked
This short puzzle catches many experienced developers, because the natural mental model of a set is that it removes equal elements, and "abc" and "xyz" are clearly not equal. The surprise reveals how sorted collections really decide identity, which matters in production code that sorts by one field, such as orders by date or players by score, and quietly loses data. Interviewers ask it to see whether we know that TreeSet relies on its comparator alone. In this answer, we will recap how TreeSet stores elements, trace the three add calls, explain why compare decides duplicates, fix the comparator, and look at what an inconsistent comparator does to the Set contract.
1A Quick Recap of How TreeSet Stores Elements
A TreeSet keeps its elements in a red-black tree, a balanced binary search tree, ordered by a Comparator we supply or by the elements' natural ordering. To add an element, it starts at the root and calls compare(newElement, nodeElement). A negative result means go left, a positive result means go right, and zero means the element is already there.
Notice that equals and hashCode play no part in this. The TreeSet Javadoc says so explicitly: the set performs all element comparisons using compareTo or compare, so two elements that the comparator considers equal are, from the set's point of view, the same element.
2Tracing the Three add Calls
Let us follow the code from the question with each step's result.
- Start at root "abc"
- compare("xyz", "abc")length 3 vs 3 -> 0
- Result is 0?YesTreat as already present, return falseNoGo left or right and continue
- Set unchanged: [abc]
4 steps in order. Play them, or step through them one at a time.
equals is never called; compare alone decides.
The surprising line is s.contains("xyz"), which returns true even though "xyz" was never stored. contains also walks the tree with compare, finds the node "abc" with the same length, and reports a match. From the set's point of view, "xyz" and "abc" are the same element, and the first one inserted is the one kept.
3Why compare Decides Duplicates
A sorted set has to place each element at one position in the order. If two elements compare as 0, the comparator is saying they occupy the same position, and a set cannot hold two elements in one position. So TreeSet treats 0 as "same element". It does not fall back to equals for a second opinion, because that would make the tree's structure depend on two different notions of sameness and searches would no longer be reliable.
The same applies to TreeMap keys, which is how TreeSet is implemented internally: a TreeSet is a TreeMap whose keys are the elements. Two keys that compare as 0 are the same key, so a put with the second key replaces the value of the first.
4Fixing the Comparator With a Tie-Breaker
We want to sort by length, but keep strings of equal length as distinct elements. thenComparing adds a second comparison used only when the first returns 0.
Now compare returns 0 only for strings that are equal in both length and content, which for strings means equal by equals. The comparator has become consistent with equals: compare(a, b) == 0 exactly when a.equals(b). That is the property every comparator used for a TreeSet or TreeMap should have, unless we deliberately want the comparator's notion of duplicates.
5What an Inconsistent Comparator Does to the Set Contract
The Set interface is defined in terms of equals: a set contains no two elements e1 and e2 such that e1.equals(e2). The original TreeSet broke the contract in the other direction: it refused "xyz" although no equal element was present. The Javadoc of TreeSet and Comparator warns that a sorted set with an ordering inconsistent with equals behaves strangely and violates the general Set contract.
The strangeness spreads to code that mixes set types. Two sets with the same visible elements may not be equal, and copying a HashSet into such a TreeSet can lose elements.
In production this shows up as missing records: a TreeSet of orders sorted by date that drops orders placed at the same moment, or a leaderboard that drops players with equal scores. The fix is always the same: break ties on a unique field, such as an id.
6Follow-up questions
Would a HashSet have the same problem?
No. A HashSet uses hashCode and equals, and "abc" and "xyz" are not equal, so it would hold all three strings, in no particular order. The issue is specific to sorted collections that rely on a comparator.
Is it ever right to use a comparator inconsistent with equals?
Occasionally, when we deliberately want the comparator's notion of duplicates, for example keeping only one string per length. Then we should document it clearly, because readers will assume normal Set behaviour. For BigDecimal, natural ordering is itself inconsistent with equals, since 2.0 and 2.00 compare as 0 but are not equal, and a TreeSet treats them as one element.
7Conclusion
In this answer, we saw that the code prints [abc, hello] because TreeSet decides duplicates with compare, not equals, and the comparator considers strings of equal length to be the same, so add("xyz") returns false and contains("xyz") even returns true. A tie-breaker with thenComparing(Comparator.naturalOrder()) makes the comparator consistent with equals and keeps all three strings. An inconsistent comparator makes a sorted set violate the Set contract and silently drop data.
Open with
It prints abc and hello, in that order. The TreeSet is built with a comparator that compares only string length, and a TreeSet never uses equals or hashCode; it walks its red-black tree with compare, and when compare returns zero it treats the new element as already present.
Then, if they want more
So adding abc makes it the root, adding xyz compares three with three, gets zero, and add returns false without storing anything, and hello has length five, so it goes to the right. Even contains of xyz returns true, because it matches abc by length.
The fix is a tie-breaker: Comparator.comparing of String::length, then thenComparing with Comparator.naturalOrder, so strings of the same length are ordered alphabetically and compare returns zero only for truly equal strings. That makes the comparator consistent with equals, and the set prints abc, xyz, hello.
The general point is that a comparator inconsistent with equals makes a sorted set violate the Set contract, which is defined by equals. In real code that looks like a TreeSet of orders sorted by timestamp that drops orders with the same timestamp, so I always add a unique field like an id as the final tie-breaker.
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
- The Collections Framework, overview, java.util, package documentation
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 this print, and why?": https://scrivio-interview-library.netlify.app/java/sets/8924669366/