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:
Iterator
over the TreeSet (ascending 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
Discussion & Comments