ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
class K {
int a, b;
K(int a, int b) { this.a = a; this.b = b; }
public int hashCode() { return 1; }
public boolean equals(Object o) {
return o instanceof K && ((K) o).a == a && ((K) o).b == b;
}
}
// in main:
Set<K> set = new HashSet<>();
set.add(new K(1, 2));
set.add(new K(3, 4));
System.out.println(set.size());- A. 1
- B. 2
- C. 0
- D. Compilation error
Correct answer: B. 2
Giving every K the same hashCode is legal (the contract only requires equal objects to share a hash, never the reverse) — it just forces both into the same bucket. HashSet then falls back to equals to tell them apart, and since (1,2) and (3,4) are not equal, both are kept: size is 2.
More OOP with C++ and Java questions
- What is printed? java class Counter { private int count = 0; void inc() { count++; } int get() { return count; } } class LoggingCounter…
- What is printed? java String a = "hel" + "lo"; String b = "hello"; System.out.println(a == b);
- Which statement about this code is correct? java class P { P(int x) { System.out.print("P" + x + " "); } } class C extends P { C() {…
- What is printed? cpp struct Base { virtual void show() { cout << "Base "; } }; struct Derived : Base { void show() override { cout <<…
- What is printed? java // in main: List<String> ls = new ArrayList<>(); List<Integer> li = new ArrayList<>()…
- Which statement about this class is correct? java class Example<T> { void method(List<String> list) { System.out.println("string-list"); }…