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 questionsThe 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.
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.
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.
Keep practicing
Take the free 1Z0-809 practice test
Ten exam-style questions with answers and explanations, plus the exam facts and study guides.
More questions
Other 1Z0-809 practice questions
- Question 2Given: class Student { String course, name, city; public Student (String name, String cou…
- Question 3Given: class Worker extends Thread { CyclicBarrier cb; public Worker(CyclicBarrier cb) { …
- Question 4Given the code fragment: Path file = Paths.get (“courses.txt”); // line n1 Assume the cou…
- Question 5Given that /green.txt and /colors/yellow.txt are accessible, and the code fragment: Path …
- Question 6Given the code fragment:List<String> empDetails = Arrays.asList(“100, Robin, HR”,“200, Ma…
- Question 7Given the code fragment: List str = Arrays.asList (“my”, “pen”, “is”, “your’, “pen”); Pre…
