1Z0-809 practice question 24 of 25

Given: class Vehicle { int vno; String name; public Vehicle (int vno, String name) { this.vno = vno,; this.name = name; } public String toString () { return vno + “:” + name; } } and this code fragment: Set vehicles = new TreeSet (); vehicles.add(new Vehicle (10123, “Ford”)); vehicles.add(new Vehicle (10124, “BMW”)); System.out.println(vehicles); What is the result?

Full set: 196 questions
Answer options
A: 10123 Ford10124 BMW
B: 10124 BMW10123 Ford
C: A compilation error occurs.
D: A ClassCastException is thrown at run time. Correct answer
Correct Answer:
D. A ClassCastException is thrown at run time.
Explanation

The code creates a TreeSet, which is a sorted set. For a TreeSet to sort its elements, the elements must either implement the java.lang.Comparable interface (for natural ordering) or a java.util.Comparator must be supplied to the TreeSet's constructor. The Vehicle class does not implement Comparable, and no Comparator is provided. When the second add method is called, the TreeSet attempts to compare the new Vehicle object with the existing one, which requires casting the element to Comparable. Since Vehicle cannot be cast to Comparable, a ClassCastException is thrown at runtime.

Why Incorrect

A. The program throws a runtime exception before it can print the set's contents. The elements are not successfully added and sorted.
B. The program throws a runtime exception. This output implies successful insertion and sorting, which does not happen.
C. The code is syntactically valid and will compile successfully. The error is a runtime type issue, not a compile-time one.

References

1. Oracle Corporation. (2021). Class TreeSet. Java® SE 17 Platform API Specification. Retrieved from https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/TreeSet.html. (The documentation states that elements must be mutually comparable, throwing a ClassCastException if they are not).

2. Bloch, J. (2018). Effective Java (3rd ed.). Addison-Wesley Professional. Item 14: "Consider implementing Comparable," explains that classes for value objects should implement Comparable to be used in sorted collections like TreeSet.

Scroll to Top