ProgrammingVery hardTCS NQT Digital · Accenture Advanced
What is printed?
What is printed?
class K {
int v;
K(int v) { this.v = v; }
public boolean equals(K o) { return o != null && v == o.v; }
public int hashCode() { return v; }
}
// main:
Set<K> s = new HashSet<>();
s.add(new K(1)); s.add(new K(1));
System.out.print(s.size() + " " + s.contains(new K(1)) + " " + new K(1).equals(new K(1)));- A. 1 true true
- B. 2 true true
- C. 2 false true
- D. 1 false true
Correct answer: C. 2 false true
equals(K) overloads, not overrides, equals(Object); HashSet uses the inherited identity equals, so two entries and contains is false. A direct call with static type K picks equals(K).
More OOP with C++ and Java questions
- What does new D().w() return? java interface A { default String w() { return "A"; } } interface B extends A { default String w() { return…
- What is printed? java class A { int a = f("a"); { f("i"); } A() { f("c"); } int f(String s) { System.out.print(s); return 1; } int b =…
- What is printed? java class A { static int x = init("Ax"); static int init(String s) { System.out.print(s); return 1; } } class B extends…
- What is printed? java List<Integer> l = new ArrayList<>(List.of(10, 20, 30, 1)); l.remove(1); l.remove(Integer.valueOf(1))…
- What is printed? java Object[] o = new String[1]; try { o[0] = 1; System.out.print("T"); } catch (ArrayStoreException e) {…
- What is printed? java int i = 1; i = i++ + ++i; int j = 5; j += j++ 2; System.out.print(i + " " + j);