ProgrammingVery hardProduct-company placement · GATE CS

What is printed?

What is printed?
class P {
    int v;
    P(int v) { this.v = v; }
    public boolean equals(P o) { return o.v == v; }
}
// in main:
List<P> list = new ArrayList<>();
list.add(new P(1));
System.out.print(new P(1).equals(new P(1)) + " " + list.contains(new P(1)));
  1. A. true true
  2. B. false false
  3. C. true false
  4. D. false true

Correct answer: C. true false

equals(P) overloads rather than overrides equals(Object). The direct call has a P argument and picks the overload (true), but ArrayList.contains calls equals(Object), which is still Object's identity check (false). @Override would have caught this.

More OOP with C++ and Java questions

Exams that ask this topic