Learning Tips | Published Nov 15, 2026 | 7 min read

Java equals() and hashCode(): How HashMap Keys Really Work

Understand the Java equals() and hashCode() contract with a practical HashMap example, implementation checklist and debugging tips.

Java equals and hashCode guide with a HashMap key example

A Java class can look like the same key to a person but behave like a different key in a HashMap. The reason is the contract between equals() and hashCode(). This guide shows how the two methods work together, how to implement them, and how to diagnose common lookup bugs.

The short rule

If two objects are equal according to equals(), they must return the same value from hashCode(). The reverse is not required: two unequal objects may have the same hash code. A hash code helps a hash-based collection find a candidate bucket; equality then determines whether the key matches.

This is why overriding only equals() can break lookups in HashMap and membership checks in HashSet.

A small example of the bug

Suppose a course platform identifies a learner by a stable numeric ID. Two separately created objects with the same ID should represent the same logical learner:

final class Learner {
    private final int id;
    private final String name;

    Learner(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) return true;
        if (!(other instanceof Learner)) return false;
        Learner learner = (Learner) other;
        return id == learner.id;
    }
}

The equals() method compares IDs, but hashCode() is still inherited from Object. That default implementation is based on object identity, so two different Learner instances can be equal while returning different hash codes. This violates the contract used by hash-based collections.

For example, after storing one object as a key, a lookup using a second object with the same ID may search a different bucket and fail to find the mapping.

Implement both methods using the same equality fields

Use the same fields for equality and hashing. Here is one Java 8-compatible implementation:

import java.util.Objects;

final class Learner {
    private final int id;
    private final String name;

    Learner(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) return true;
        if (!(other instanceof Learner)) return false;
        Learner learner = (Learner) other;
        return id == learner.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

Because the class defines equality using only id, the hash code also uses only id. The name is not part of identity in this example. If your domain says the name also determines equality, include it in both methods.

Test the behavior with a HashMap

Map<Learner, String> progress = new HashMap<>();

Learner storedKey = new Learner(42, "Asha");
Learner lookupKey = new Learner(42, "Asha");

progress.put(storedKey, "Java collections");

System.out.println(storedKey.equals(lookupKey)); // true
System.out.println(progress.get(lookupKey));     // Java collections

The two variables refer to different objects, but the key fields define them as equal. Their matching hash codes let the map search the right bucket, and equals() confirms the key match.

Requirements your equals() method must preserve

The Java API specifies that equals() should be reflexive, symmetric, transitive and consistent, and that a non-null object must compare false to null. The hash-code contract requires a stable result during an execution while equality-relevant information stays unchanged, and equal objects must have equal hash codes. Hash collisions are allowed.

In practice, this means:

  • Compare objects in both directions when checking symmetry: if a.equals(b) is true, b.equals(a) must also be true.
  • Keep the equality fields consistent between equals() and hashCode().
  • Avoid changing fields used in equality while an object is a key in a hash-based collection.
  • Do not expect different objects to always have different hash codes.

Why mutable keys are dangerous

If a field used by hashCode() changes after an object is inserted into a HashMap, a later lookup can calculate a different bucket. The entry may still exist in the map, but searching with the changed key can fail. Prefer immutable key fields, or remove the key before changing equality-relevant data and insert it again afterward.

Using records in newer Java versions

For a simple immutable data carrier, a Java record supplies value-based equals() and hashCode() implementations derived from its components:

record LearnerKey(int id) {}

Map<LearnerKey, String> progress = new HashMap<>();
progress.put(new LearnerKey(42), "Java collections");

System.out.println(progress.get(new LearnerKey(42)));

Records require a newer Java version than Java 8. For older projects, ordinary classes can implement both methods explicitly or use an IDE-generated implementation, followed by tests that cover equal and unequal instances.

A quick debugging checklist

  1. Does equals() compare the fields that define logical identity?
  2. Does hashCode() use those same fields?
  3. Are the fields stable while the key is stored in a map or set?
  4. Do tests cover two separate but equal instances?
  5. Does equals() satisfy symmetry and transitivity?

For a structured path through Java fundamentals and collections, see the Core Java course details or explore the IT course catalog.

Official Java references

Consult Oracle's Java SE Object API for the equals() and hashCode() contracts, and the HashMap API for map lookup behavior.

Want a structured Java learning path?

Explore Jaipur Engineers course options to connect Java fundamentals, debugging, backend development and project practice in a guided learning plan.

Explore the Java program   Ask for course guidance