ProgrammingVery hardProduct-company placement · Java

What happens?

What happens?
class P { int v; P(int v) { this.v = v; } }
// in main:
Set<P> s = new TreeSet<>();
s.add(new P(1));
s.add(new P(2));
System.out.print(s.size());
  1. A. It prints 2
  2. B. Compile-time error: P is not Comparable
  3. C. A ClassCastException is thrown at run time
  4. D. It prints 1

Correct answer: C. A ClassCastException is thrown at run time

TreeSet's element type has no Comparable bound, so the code compiles; with no comparator it casts elements to Comparable when ordering them, and P is not Comparable.

More OOP with C++ and Java questions

Exams that ask this topic