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:
- Use all significant fields that influence object equality.
- For primitive types (e.g.,
int), use their values directly. - For objects (e.g.,
String email), use their ownhashCode, considering the possibility ofnull. - 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;
}