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()));
}
}- A. true
- B. false
- C. Compile-time error: List.contains needs a matching hashCode too
- 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
- What is printed? cpp template <typename T> T maxVal(T a, T b) { return a > b ? a : b; } int main() { cout << maxVal(3, 7) << " " <<…
- What happens? java interface A { default String id() { return "A"; } } interface B { default String id() { return "B"; } } class D…
- What is printed? cpp struct Base { virtual void f() = 0; void greet() { cout << "greet "; f(); } }; struct Derived : Base { void f()…
- What happens? cpp struct Shape { virtual double area() const = 0; }; int main() { Shape s; cout << s.area(); }
- What is printed? java abstract class Vehicle { abstract void move(); void start() { System.out.print("starting "); move(); } } // in main…
- What is printed? cpp class Base { public: Base(int x) { cout << "Base(" << x << ") "; } }; class Derived : public Base { public: Derived()…