Java TreeSet iteration order and duplicate handling: what sequence is printed? TreeSet map = new TreeSet(); map.add("one"); map.add("two"); map.add("three"); map.add("four"); map.add("one"); // duplicate Iterator it = map.iterator(); while (it.hasNext()) { System.out.print(it.next() + " "); }
-
Aone two three four
-
Bfour three two one
-
Cfour one three two
-
Done two three four one
-
Eone three two four
Answer
Correct Answer: four one three two
Explanation
Introduction / Context:
This question examines how java.util.TreeSet orders elements and deals with duplicates. TreeSet stores elements in a sorted order (natural ordering for String) and does not allow duplicates.
Given Data / Assumptions:
- Inserted strings: "one", "two", "three", "four", then "one" again.
- Iteration is via
Iteratorover the TreeSet (ascending order). - Natural order for Strings is lexicographical (dictionary order).
Concept / Approach: Compute the lexicographic order among the distinct values. The duplicate "one" has no effect because sets ignore duplicates. Sorted order for the distinct elements is determined by standard String comparison rules.
Step-by-Step Solution: Distinct elements are { "four", "one", "three", "two" }. Lexicographic ascending order: "four" < "one" < "three" < "two". Iteration prints: four one three two with spaces.
Verification / Alternative check: Try a Comparator.reverseOrder() TreeSet; you would then see the reverse sequence. Or use a HashSet to show undefined iteration order.
Why Other Options Are Wrong: “one two three four” would be insertion order, not TreeSet’s sorted order; “... one” at the end implies duplicates are printed, which sets prevent.
Common Pitfalls: Confusing HashSet (unordered) with TreeSet (sorted); assuming duplicates are kept; expecting insertion order.
Final Answer: four one three two