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?

A.

10123:Ford
10124:BMW

B.

10124:BMW
10123:Ford

C. A compilation error occurs.
D. A ClassCastException is thrown at run time.

题解

题目提供的程序会在第 21 行抛出 ClassCastException,因为 TreeSet 的元素必须要实作 Comparable 界面,才可以进行自动排序。