ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
class P {
int id;
P(int id) { this.id = id; }
@Override
public boolean equals(Object o) {
return o instanceof P && ((P) o).id == id;
}
}
// in main:
Set<P> s = new HashSet<>();
s.add(new P(1));
s.add(new P(1));
System.out.print(s.size() + " " + new P(1).equals(new P(1)));- A. 2 true
- B. 1 true
- C. 2 false
- D. 1 false
Correct answer: A. 2 true
equals says the objects are equal, but hashCode was not overridden, so each object keeps its identity hash and lands in a different bucket; HashSet never compares them with equals. Overriding equals requires overriding hashCode.
More OOP with C++ and Java questions
- What is printed? java System.out.print(5.0 / 0 + " "); System.out.print(0.0 / 0 + " "); try { System.out.print(5 / 0); } catch…
- What is printed? cpp struct R { int v = 0; R& inc() { v++; return this; } }; struct V { int v = 0; V inc() { v++; return this; } }; int…
- What is printed? cpp int a = 5; int &r = a; r = 10; int b = 20; r = b; b = 30; cout << a << " " << r;
- What is printed? java class R implements AutoCloseable { String n; R(String n) { this.n = n; System.out.print("o" + n + " "); } public…
- What is printed? cpp struct B { virtual void f(int x = 1) { cout << "B" << x; } }; struct D : B { void f(int x = 2) override { cout << "D"…
- What is printed? java class T { static String hi() { return "hi"; } } // in main: T t = null; System.out.print(t.hi());