Java SE 8 Programmer II — Question 101
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?
Answer options
- A. [10123:Ford, 10124:BMW]
- B. [10124:BMW, 10123:Ford]
- C. A compilation error occurs.
- D. A ClassCastException is thrown at run time.
Correct answer: A
Explanation
The correct answer is A because the TreeSet sorts the Vehicle objects based on the name attribute as defined by the compareTo method. Since 'Ford' comes before 'BMW' alphabetically, the output will reflect the ordering of the Vehicle objects as [10123:Ford, 10124:BMW]. Options B, C, and D are incorrect as there are no compilation errors or runtime exceptions in this case.