Java.Collections.How does HashMap work when trying to store two elements in it by keys with the same hashCode(), but for which equals() == false?

🎯 TL;DR:

HashMap can store multiple keys with the same hashCode() as long as equals() returns false — because it uses both hashCode() and equals() to handle collisions properly.

Let’s break it down 👇

🧠 Scenario:

You have two objects:

Object a;
Object b;

// They both return the same hash code:
a.hashCode() == b.hashCode()  ✅

// But are not equal:
a.equals(b) == false          ✅

Now you do:

map.put(a, "valueA");
map.put(b, "valueB");

❓ What happens?

Both entries will be stored in the same bucket
HashMap will NOT overwrite one with the other
Retrieval still works correctly


🔧 How Does HashMap Handle This?

Internally:

  1. Java calculates the bucket index using hashCode():
index = (n - 1) & hash
  1. If two keys have the same index, it checks the linked list or tree in that bucket.
  2. For each entry, it checks:
    • If the hash is equal
    • Then if equals() returns true

If equals() is false, it:

  • Keeps searching the bucket chain (or tree)
  • Eventually adds the new entry to the end of the chain

🧪 Real Example:

class CustomKey {
    private final String name;

    CustomKey(String name) {
        this.name = name;
    }

    public int hashCode() {
        return 42; // Force collision!
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof CustomKey)) return false;
        return !this.name.equals(((CustomKey) o).name); // Reverse logic!
    }

    public String toString() {
        return name;
    }
}

public class Demo {
    public static void main(String[] args) {
        Map<CustomKey, String> map = new HashMap<>();
        CustomKey a = new CustomKey("Alice");
        CustomKey b = new CustomKey("Bob");

        map.put(a, "Value A");
        map.put(b, "Value B");

        System.out.println(map);          // Both entries appear
        System.out.println(map.get(a));   // "Value A"
        System.out.println(map.get(b));   // "Value B"
    }
}

✅ Even though both keys have hashCode() = 42,
✅ They are not equal, so HashMap treats them as distinct entries

✅ Why This Works Well

HashMap uses this combo check:

if (e.hash == hash && (e.key.equals(key)))
  • So same hash doesn’t mean same key
  • Collision resolution (via chaining or treeing) handles same-hash-but-unequal keys

🧠 TL;DR (Again):

✅ You can store multiple keys with the same hashCode() in a HashMap
✅ As long as equals() says they’re different, they’ll be stored separately
HashMap handles this gracefully using chaining or tree bins inside each bucket

This entry was posted in Без рубрики. Bookmark the permalink.