ProgrammingVery hardGATE CS · TCS Digital · Advanced

What is printed?

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

Correct answer: B. false 1 false true

The entry stays in the bucket for hash 1. After k.v = 2 the lookups go to another bucket and fail (contains and remove false, size still 1); once v is back to 1 the same bucket is probed and the identical object is found.

More OOP with C++ and Java questions

Exams that ask this topic