ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Vehicle implements Comparable<Vehicle> {
    int speed;
    Vehicle(int s) { speed = s; }
    public int compareTo(Vehicle o) { return Integer.compare(speed, o.speed); }
}
public class Main {
    public static void main(String[] args) {
        java.util.List<Vehicle> list = new java.util.ArrayList<>();
        list.add(new Vehicle(50));
        list.add(new Vehicle(20));
        list.add(new Vehicle(80));
        java.util.Collections.sort(list);
        for (Vehicle v : list) System.out.print(v.speed + " ");
    }
}
  1. A. 50 20 80
  2. B. 80 50 20
  3. C. 20 50 80
  4. D. Compile-time error: Collections.sort needs a Comparator, not Comparable

Correct answer: C. 20 50 80

Collections.sort(List<T>) works directly on types implementing Comparable<T>, using compareTo() to order them. compareTo() here compares by speed ascending, so sorting produces 20, 50, 80.

More OOP with C++ and Java questions

Exams that ask this topic