ProgrammingHardTCS NQT · Infosys interview pattern

How many of the following statements about equals() and hashCode() in Java are correct? (i) If a.equals(b) is true, a.hashCode() must equal b.hashCode(). (ii) If a.hashCode() == b.hashCode(), then a.equals(b) must be true. (iii) Overriding equals() without overriding hashCode() can make a HashSet keep two “equal” objects. (iv) Object’s default equals() compares references.

  1. A. 1
  2. B. 2
  3. C. 3
  4. D. 4

Correct answer: C. 3

(i), (iii) and (iv) are correct. (ii) is false: different objects may collide on the same hash code. (iii) happens because HashSet first looks in the bucket chosen by hashCode, so equal objects with different hash codes land in different buckets.

More OOP with C++ and Java questions

Exams that ask this topic