ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
public class Main {
    static class Base {
        public String toString() { return "Base"; }
        public boolean equals(Object o) { return o instanceof Base; }
    }
    public static void main(String[] args) {
        java.util.List<Base> list = new java.util.ArrayList<>();
        list.add(new Base());
        System.out.println(list.contains(new Base()));
    }
}
  1. A. true
  2. B. false
  3. C. Compile-time error: List.contains needs a matching hashCode too
  4. D. NullPointerException

Correct answer: A. true

List.contains() uses equals() (not hashCode(), which only matters for hash-based collections like HashSet/HashMap), iterating and checking each stored element against the argument. Since equals() only checks instanceof Base, any two Base instances compare equal, so contains() returns true.

More OOP with C++ and Java questions

Exams that ask this topic