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());- A. true true 1
- B. true false 1
- C. false true 1
- 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
- What happens when this code runs? java Integer n = null; boolean flag = true; Integer a = flag ? n : Integer.valueOf(0)…
- Which lines fail to compile? java short s = 1; s = s + 1; // L1 s += 1; // L2 char c = 'A'; c++; // L3 final int k = 10; byte b1 = k; //…
- Which of these four fragments compiles? (FileReader's constructor throws FileNotFoundException, a subclass of IOException.) java // A try…
- What is printed? java class R implements AutoCloseable { public void close() { throw new IllegalStateException("close"); } } // in main…
- What is printed? java class T { static int a = T.b + 1; static int b = 5; static int c = b + 1; } // in main: System.out.print(T.a + " " +…
- What is printed? java class K { static final int C = 10; static final Integer D = 20; static { System.out.print("K "); } } // in main…