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 + " ");
}
}- A. 50 20 80
- B. 80 50 20
- C. 20 50 80
- 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
- What is printed? cpp struct Base { virtual Base& self() { cout << "Base::self "; return this; } }; struct Derived : Base { Derived& self()…
- What is printed? java enum Status { ACTIVE, INACTIVE, BANNED; boolean isUsable() { return this == ACTIVE; } } public class Main { public…
- What happens when this is compiled? java enum Operation { ADD { public int apply(int a, int b) { return a + b; } }, MULTIPLY { public int…
- What is printed? cpp struct Logger { Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete; Logger() { cout << "Ctor…
- What is printed? java class Base { Base() { System.out.print("Base "); } } abstract class Middle extends Base { Middle() {…
- What is printed? cpp class Matrix { public: Matrix operator(const Matrix &o) const { cout << "mul "; return Matrix(); } Matrix…