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<Vehicle>vehicles = new TreeSet <> (); vehicles.add(new Vehicle (10123, "Ford")); vehicles.add(new Vehicle (10124, "BMW")); System.out.println(vehicles); What is the result?
Click on the arrows to vote for the correct answer
A. B. C. D.D.
The given code defines a class Vehicle
with two instance variables vno
and name
. The class has a constructor that initializes these variables and a toString()
method that returns a string representation of the Vehicle
object.
In the code fragment, a TreeSet
of Vehicle
objects is created and two Vehicle
objects are added to it using the add()
method. The TreeSet
is then printed using the System.out.println()
method.
The TreeSet
is a collection that stores its elements in sorted order. In order to maintain the sorted order, the Vehicle
class must implement the Comparable
interface and provide an implementation for the compareTo()
method. If the compareTo()
method is not implemented, a ClassCastException
will be thrown at runtime.
In this case, the Vehicle
class does not implement the Comparable
interface, so the TreeSet
will use the default ordering, which is based on the natural order of the elements. Since Vehicle
objects are not comparable, a ClassCastException
will be thrown at runtime.
Therefore, the correct answer is option D: A ClassCastException
is thrown at runtime.