A `Person` object will be used as a key in a `HashMap`. Write a correct implementation of the `equals()` and `hashCode()` methods for the `Person` class below.
Java interview question for Advanced practice.
Answer
To correctly use Person objects as keys in a HashMap, the equals() and hashCode() methods must be overridden based on the object's fields. Logical equality for a Person should depend on both name and age. A correct implementation would be: java @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, age); } This implementation adheres to the contract: the equals method checks for null, type compatibility, and then compares both the age and name fields for equality. The hashCode method uses Objects.hash(), a utility method that computes a hash code based on the same fields (name and age), ensuring that two Person objects deemed equal will always have the same hash code.
Explanation
Modern IDEs like IntelliJ IDEA and Eclipse can automatically generate correct and robust equals() and hashCode() implementations for you, which is often safer than writing them by hand.