1Z0-809 · Question #92
Given: class Vehicle implements Comparable<Vehicle>{ int vno; String name; public Vehicle (int vno, String name) { this.vno = vno; this.name = name; } public String toString () { return vno + ":" +…
The correct answer is B. [10124:BMW, 10123:Ford]. TreeSet maintains elements in sorted order using the compareTo method, not insertion order. Since compareTo sorts by name alphabetically, "BMW" < "Ford" lexicographically, so BMW appears first - producing [10124:BMW, 10123:Ford]. Why the distractors are wrong: A is wrong…
Question
Options
- A[10123:Ford, 10124:BMW]
- B[10124:BMW, 10123:Ford]
- CA compilation error occurs.
- DA ClassCastException is thrown at run time.
How the community answered
(28 responses)- A4% (1)
- B82% (23)
- C11% (3)
- D4% (1)
Explanation
TreeSet maintains elements in sorted order using the compareTo method, not insertion order. Since compareTo sorts by name alphabetically, "BMW" < "Ford" lexicographically, so BMW appears first - producing [10124:BMW, 10123:Ford].
Why the distractors are wrong:
- A is wrong because
TreeSetnever preserves insertion order; that'sLinkedHashSet's job. - C is wrong because
Vehiclecorrectly implementsComparable<Vehicle>, so the compiler is satisfied. - D is wrong because
ClassCastExceptionwould occur only if the class did not implementComparable(orComparatorwasn't provided) - here, it does.
Memory tip: Think "Tree = sorted, Hash = unordered, LinkedHash = insertion order." Whenever you see TreeSet or TreeMap, ask yourself "what does compareTo return?" - that determines the sort key, not the field order or insertion sequence.
Community Discussion
No community discussion yet for this question.