ProgrammingHardTCS NQT · Infosys pattern

Which statement about overriding equals() correctly describes the contract that must hold?

  1. A. If equals() is overridden, hashCode() may be left as the default identity hash with no consequence
  2. B. equals() must always compare object references, never field values
  3. C. equals() only needs to be reflexive; symmetry and transitivity are optional for custom classes
  4. D. equals() must be reflexive, symmetric, transitive, and consistent, and x.equals(null) must always return false

Correct answer: D. equals() must be reflexive, symmetric, transitive, and consistent, and x.equals(null) must always return false

The Object.equals() contract requires reflexivity (x.equals(x)), symmetry (x.equals(y) iff y.equals(x)), transitivity, consistency across repeated calls (if no mutation), and x.equals(null) == false. Breaking any of these, or overriding equals() without hashCode(), causes subtle bugs in hash-based collections.

More OOP with C++ and Java questions

Exams that ask this topic