ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
class K {
    int id;
    K(int id) { this.id = id; }
    public boolean equals(Object o) {
        return o instanceof K && ((K) o).id == id;
    }
    public int hashCode() { return id; }
}
// in main:
Set<K> set = new HashSet<>();
K k = new K(1);
set.add(k);
k.id = 2;
System.out.print(set.contains(k) + " ");
System.out.print(set.contains(new K(1)) + " ");
set.add(k);
System.out.print(set.size());
  1. A. true true 1
  2. B. true false 1
  3. C. false true 1
  4. D. false false 2

Correct answer: D. false false 2

The object was stored under hash 1. After k.id = 2, contains(k) looks for hash 2 and does not find the old entry (HashMap also compares the cached hash), so false. contains(new K(1)) does look under hash 1 and finds the stored object, but equals compares id 1 with the stored object's current id 2, so false again. set.add(k) then stores the same object a second time under hash 2, and the size becomes 2. Mutating a field used by hashCode while an object is inside a hash set leaves it unreachable.

More OOP with C++ and Java questions

Exams that ask this topic