ProgrammingVery hardProduct company OA

What is printed?

What is printed?
class Node {
    int val;
    Node(int v) { val = v; }
    @Override
    public int hashCode() { return 42; }
    @Override
    public boolean equals(Object o) {
        return o instanceof Node && ((Node) o).val == val;
    }
}
// in main:
Set<Node> set = new HashSet<>();
for (int i = 0; i < 1000; i++) set.add(new Node(i));
System.out.println(set.size());
  1. A. 1000
  2. B. 1
  3. C. 0
  4. D. It never terminates

Correct answer: A. 1000

Every Node gets the same hashCode (42) — a deliberately bad but legal hash function — so all 1000 objects collide into one bucket. HashSet still works correctly (just slowly, degrading to a linear scan with equals()), and since each val 0..999 is distinct, equals() correctly treats all 1000 as unique: size 1000.

More OOP with C++ and Java questions

Exams that ask this topic