hashCode() Override in Java
Problem
Java's contract requires that two objects considered equal by equals() must also produce the same hashCode() — breaking that rule causes subtle bugs in hash-based collections like HashMap and HashSet.
Create a Person class where two equal-by-value objects also produce the same hash code.
Java Program
import java.util.Objects;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person other = (Person) o;
return age == other.age && name.equals(other.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age); // built from the same fields equals() compares
}
public static void main(String[] args) {
Person p1 = new Person("Alice", 30);
Person p2 = new Person("Alice", 30);
System.out.println("Same hash code: " + (p1.hashCode() == p2.hashCode()));
}
}Output
Core Logic
Building the hash code from the exact same fields that equals() compares guarantees that any two objects equals() considers equal will always hash to the same value.
- 1
equals()is overridden first, comparingnameandagethe same way as any value-equality check. - 2
hashCode()is overridden to returnObjects.hash(name, age)— built from the identical set of fieldsequals()uses. - 3Because both methods derive from the same fields, two Person objects with matching
nameandageare guaranteed to produce matching hash codes. - 4
Objects.hash(...)combines any number of fields into a single well-distributed int, without needing to hand-write the combining formula.
Person("Alice", 30) objects report the same hashCode() value, since both derive it from the identical name and age.Key Point: If hashCode() were left at its default (identity-based) while equals() was overridden, two equal Person objects could report different hash codes — which would make them silently fail to be found in a HashSet or as HashMap keys, since those structures check the hash code before ever calling equals().