Pregunta de entrevista de Google

What is the relationship between equals(Object o) and hashCode() in Java? How would you implement each method?

Respuestas de entrevistas

Anónimo

7 ene 2010

A class which overrides one must override the other such that objects which .equals() each other generate identical hash codes. Typically, what this would mean for implementation is that every field or attribute (including type depending on the constraints - maybe you want two objects of a given parent type to be equal to each other, so you check the parent type instead of the exact type) which is compared in the .equals() method must be used as input in the hashCode() algorithm. Something which doesn't affect object equality should never be hashed.

1

Anónimo

24 abr 2010

You need to be very careful to preserve transitivity if you allow a subclass to be equal to a super class. The super class needs to be designed for this and you have to rely on all other subclasses also being implemented correctly