Java ProgramsOOPhashCode() Override

hashCode() Override in Java

intermediate·  OOP  ·  Object Class

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.

Input
new Person("Alice", 30).hashCode() vs new Person("Alice", 30).hashCode()
Output
Same hash code: true

Java Program

Java
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

Same hash code: true

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.

How It Works
  1. 1equals() is overridden first, comparing name and age the same way as any value-equality check.
  2. 2hashCode() is overridden to return Objects.hash(name, age) — built from the identical set of fields equals() uses.
  3. 3Because both methods derive from the same fields, two Person objects with matching name and age are guaranteed to produce matching hash codes.
  4. 4Objects.hash(...) combines any number of fields into a single well-distributed int, without needing to hand-write the combining formula.
Two separately-constructed 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().

Key Concepts

@OverridehashCode()Objects.hash()equals/hashCode contract

Related Programs