ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class K {
    int a, b;
    K(int a, int b) { this.a = a; this.b = b; }
    public int hashCode() { return 1; }
    public boolean equals(Object o) {
        return o instanceof K && ((K) o).a == a && ((K) o).b == b;
    }
}
// in main:
Set<K> set = new HashSet<>();
set.add(new K(1, 2));
set.add(new K(3, 4));
System.out.println(set.size());
  1. A. 1
  2. B. 2
  3. C. 0
  4. D. Compilation error

Correct answer: B. 2

Giving every K the same hashCode is legal (the contract only requires equal objects to share a hash, never the reverse) — it just forces both into the same bucket. HashSet then falls back to equals to tell them apart, and since (1,2) and (3,4) are not equal, both are kept: size is 2.

More OOP with C++ and Java questions

Exams that ask this topic