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)));
  1. A. 2 true
  2. B. 1 true
  3. C. 2 false
  4. 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

Exams that ask this topic