ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Key {
    final String name;
    Key(String n) { name = n; }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        return name.equals(((Key) o).name);
    }
    @Override
    public int hashCode() { return name.hashCode(); }
}
public class Main {
    public static void main(String[] args) {
        Map<Key, Integer> map = new HashMap<>();
        map.put(new Key("x"), 1);
        map.put(new Key("x"), 2);
        System.out.print(map.size() + " " + map.get(new Key("x")));
    }
}
  1. A. 1 1
  2. B. 1 2
  3. C. 2 1
  4. D. 2 2

Correct answer: B. 1 2

Both Key("x") instances are equal and have the same hashCode, so the second put() replaces the value for the existing key rather than adding a new entry: size stays 1, and the stored value becomes 2 (the later put wins). A fresh Key("x") lookup also matches via equals/hashCode, returning 2.

More OOP with C++ and Java questions

Exams that ask this topic