Sobes.tech
Junior — Middle

What steps are necessary to correctly implement the hashCode method for a class containing fields id, age, and email?

sobes.tech AI

Answer from AI

To correctly implement the hashCode method in a class with fields id, age, and email, you should:

  1. Use all significant fields that influence object equality.
  2. For primitive types (e.g., int), use their values directly.
  3. For objects (e.g., String email), use their own hashCode, considering the possibility of null.
  4. Combine the hashes of the fields by multiplying by a prime number (usually 31) to reduce collisions.

Example implementation:

@Override
public int hashCode() {
    int result = Integer.hashCode(id);
    result = 31 * result + Integer.hashCode(age);
    result = 31 * result + (email != null ? email.hashCode() : 0);
    return result;
}
What steps are necessary to correctly implement the… - sobes.tech