Java TreeSet iteration order and duplicate handling: what sequence is printed?\n\nTreeSet map = new TreeSet();\nmap.add("one");\nmap.add("two");\nmap.add("three");\nmap.add("four");\nmap.add("one"); // duplicate\nIterator it = map.iterator();\nwhile (it.hasNext()) {\n System.out.print(it.next() + " ");\n}

Difficulty: Easy

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 Iterator over 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

More Questions from Objects and Collections

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion