01 / 20

Hashing in
HashMap & HashSet

Discover how Java transforms objects into bucket indices, why hashCode() and equals() are inseparable, and what happens when collisions occur beneath the surface.

Computer Science Java Data Structures

What Is Hashing?

Hashing is the process of converting any object into a fixed-size integer called a hash code. Java's hashCode() method produces this integer, and the collection uses it to decide which bucket the object lands in.

hashCode()
Returns an int for any object. Defined in java.lang.Object.
Bucket Index
Computed as \( \text{hashCode} \mathbin{\&} (n - 1) \) where \(n\) is the array length.
\(O(1)\) Average
Good hashing gives constant-time put, get, and contains.

The hashCode Contract

Java's documentation mandates a strict contract between hashCode() and equals(). Violating it causes silent, hard-to-debug failures in every hash-based collection.

1
Consistency: Calling hashCode() multiple times on the same object must return the same value within one program run (assuming no mutation of fields used in equals).
2
Equal objects, equal codes: If a.equals(b) is true, then a.hashCode() == b.hashCode() must also be true.
3
Unequal objects may collide: Different objects can share the same hash code: this is a collision, not a bug.

Inside a HashMap: Buckets

Bucket Array (length = 8) 0 1 2 3 4 5 6 7 null null null null null null "apple" → 42 "kiwi" → 7 null "banana" → 13 null Collision! "apple" & "kiwi" both map to bucket 2

Computing the Bucket Index

Java's HashMap does not use modulo. Instead, it uses a bitwise AND with a power-of-two table size for speed:

Example: "apple".hashCode() = 93029210 Binary (low 16 bits): 0100 1001 1001 1010 table.length - 1 = 15: 0000 0000 0000 1111 AND result (index): 0000 0000 0000 1010 = 10 "apple" goes to bucket 10 (in a table of length 16)

What Happens During a Collision?

When two different keys produce the same bucket index, Java stores both entries in that bucket using a linked list. On lookup, it walks the chain, calling equals() on each key until it finds a match.

1
Few collisions: The chain is short: lookup stays near \(O(1)\).
2
Many collisions: The chain grows long: lookup degrades to \(O(n)\).
3
Treeification (Java 8+): When a single bucket exceeds 8 nodes, the linked list converts to a red-black tree, capping worst-case at \(O(\log n)\).

HashSet Is Just a HashMap

A HashSet doesn't have its own hashing logic. Internally, it delegates everything to a private HashMap where each element is a key and the value is a shared dummy object.

// Simplified HashSet source public class HashSet<E> { private HashMap<E, Object> map; private static final Object PRESENT = new Object(); public boolean add(E e) { return map.put(e, PRESENT) == null; } }

hashCode vs equals

hashCode() equals()
Purpose Find the bucket Confirm identity within bucket
Return type int boolean
Speed Very fast (arithmetic) Slower (field-by-field comparison)
When called First: to locate bucket Second: to match within bucket
Can collide? Yes (expected) No (must be precise)
Default (Object) Memory address based Reference equality (==)

Load Factor & Resizing

The load factor controls when the internal array doubles in size. Java's default is 0.75: when the number of entries exceeds 75% of the table's capacity, the table rehashes all entries into a new, larger array.

Default capacity
\(16\) buckets at creation
Threshold
\(16 \times 0.75 = 12\) entries triggers resize
New size
Always doubles: \(16 \to 32 \to 64 \to \ldots\)

How to Override Correctly

1
Identify significant fields: Decide which fields define logical equality (e.g., id, name).
2
Override equals(): Compare only those fields. Use instanceof check, cast, then field-by-field comparison.
3
Override hashCode(): Compute from the same fields used in equals(). Use Objects.hash(field1, field2, ...).
4
Never use mutable fields: If a field changes after insertion, the hash code changes, and the object becomes unreachable in its original bucket.
5
Test symmetry: Verify that a.equals(b) && b.equals(a) and both yield the same hashCode.

Example 1: Correct Override

public class Student { private final int id; private final String name; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Student s)) return false; return id == s.id && Objects.equals(name, s.name); } @Override public int hashCode() { return Objects.hash(id, name); } }

Example 2: Broken Contract

public class Point { private int x, y; @Override public boolean equals(Object o) { if (!(o instanceof Point p)) return false; return x == p.x && y == p.y; } // hashCode() NOT overridden! }
Set<Point> set = new HashSet<>(); set.add(new Point(1, 2)); set.contains(new Point(1, 2)); // false!

Example 3: The Mutable Key Trap

Map<List<String>, Integer> map = new HashMap<>(); List<String> key = new ArrayList<>(); key.add("a"); map.put(key, 42); // stored at bucket based on ["a"] key.add("b"); // mutation changes hashCode! map.get(key); // null! Looks in wrong bucket
Before mutation key.hashCode() = 128 Stored in bucket: 128 & 15 = 0 After mutation key.hashCode() = 4066 Lookup searches bucket: 4066 & 15 = 2 Entry stuck here Lookup goes here

Common Mistakes

✕ Override only equals()
Equal objects land in different buckets because hashCode() still uses the default memory address.
✕ Use mutable fields
Mutating a key after insertion orphans the entry: it exists but can never be found.
✕ Return constant hashCode
Returning the same value (e.g., return 1;) is legal but puts all entries in one bucket: \(O(n)\) performance.
✕ Confuse == with equals()
== compares references. Inside equals(), you must compare field values, not object identity.
✕ Forget null checks
A robust equals() must handle null input and different types gracefully without throwing exceptions.

Summary at a Glance

Concept Key Detail Why It Matters
hashCode() Returns int, picks bucket Wrong bucket = lost entry
equals() Returns boolean, confirms match Incorrectly returns false = allows duplicate keys
Contract equal \(\to\) same hashCode Broken contract = silent bugs
Collision Same bucket, different keys Too many = \(O(n)\) degradation
Load factor Default 0.75, triggers resize Rehashing is expensive
Immutability Keys must not change after put Mutation orphans entries

Question 1 of 5

Two objects a and b satisfy a.equals(b) == true. According to the hashCode contract, which statement must be true?

Question 2 of 5

A class overrides equals() based on an id field but does not override hashCode(). What happens when two logically equal objects are added to a HashSet?

Question 3 of 5

A HashMap has a table length of 16. An object's hashCode() returns 35. Using Java's index formula \( \text{hashCode} \mathbin{\&} (\text{length} - 1) \), which bucket does the object go to?

Question 4 of 5

You use an ArrayList as a key in a HashMap, insert an entry, then add an element to that list. What is the result of calling map.get(key)?

Question 5 of 5

A class overrides hashCode() to always return 1. The code compiles and the contract is technically not violated. What is the practical consequence?