equals() and hashCode() for a HashMap Key
javaJavabeginnerinterview-prepjava
An immutable class with a correct equals and hashCode pair, used as a HashMap key, so a lookup with a different but equal object finds the entry.
import java.util.*;
public class EqualsHashCodeDemo {
public static void main(String[] args) {
Map<Person, String> roles = new HashMap<>();
roles.put(new Person("Asha", 31), "admin");
System.out.println(roles.get(new Person("Asha", 31))); // admin (an equal key finds the entry)
System.out.println(roles.get(new Person("Asha", 32))); // null (a different age is a different key)
System.out.println(new Person("Asha", 31).hashCode() == new Person("Asha", 31).hashCode()); // true
}
}
// Immutable (final fields), so it is safe as a key. equals() and hashCode() use the same fields.
final class Person {
private final String name;
private final int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
return o instanceof Person other && age == other.age && Objects.equals(name, other.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}