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)));
  1. A. 1 true true
  2. B. 2 true true
  3. C. 2 false true
  4. 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

Exams that ask this topic