nerdexam
Oracle

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

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 + ":" + name; } public int compareTo(Vehicle o) { return this.name.compareTo(o.name); } and this code fragment: Set<Vehicle> vehicles = new TreeSet <>(); vehicles.add(new Vehicle (10123, "Ford")); vehicles.add(new Vehicle (10124, "BMW")); System.out.println(vehicles); What is the result?

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)
  • A
    4% (1)
  • B
    82% (23)
  • C
    11% (3)
  • D
    4% (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 TreeSet never preserves insertion order; that's LinkedHashSet's job.
  • C is wrong because Vehicle correctly implements Comparable<Vehicle>, so the compiler is satisfied.
  • D is wrong because ClassCastException would occur only if the class did not implement Comparable (or Comparator wasn'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.

Full 1Z0-809 Practice