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());- A. It prints 2
- B. Compile-time error: P is not Comparable
- C. A ClassCastException is thrown at run time
- 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
- Which constructors cause compile-time errors? java class F { final int x; F() { } // constructor 1 F(int v) { x = v; x = v + 1; } //…
- What is printed? java Map<String, Integer> m = new HashMap<>(); m.compute("a", (k, v) -> v == null ? 1 : v + 1); m.compute("a", (k, v) ->…
- What is printed? java Map<String, String> h = new HashMap<>(); h.put("k", null); System.out.print(h.size() + " "); Map<String, String> c =…
- What is printed? java List<Integer> e = Collections.emptyList(); System.out.print(e.size() + " "); e.add(1);
- What is printed? java System.out.print(String.valueOf((Object) null) + " "); System.out.print(String.valueOf(null));
- What is printed? java // static methods of the main class: static void f(int... a) { System.out.print("V"); } static void f(Integer a…