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));- A. true 1 true true
- B. false 1 false true
- C. false 1 true true
- 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
- What is printed? java Number[] n = new Integer[2]; n[0] = 1; try { n[1] = 2.5; } catch (ArrayStoreException e) { System.out.print("ASE ")…
- What is printed? java String a = "ab"; String b = "a"; String c = b + "b"; final String d = "a"; String e = d + "b"; System.out.print((a…
- What is printed? java interface A { default String m() { return "A"; } } interface B extends A { default String m() { return "B"; } }…
- What is printed? java class P { String n = "P"; static String s() { return "Ps"; } String t() { return "Pt"; } } class C extends P {…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct M { const char n; M(const char s) : n(s) { } ~M() { cout <<…
- What is printed? (C++17, assume <iostream> and using namespace std) cpp struct P { P(const char s) { cout << s; } }; struct Q { P y{"y"}…