Sub topic 6
Why HashMap and HashSet Need Both Methods
Assume you can write Java classes, use List, Set, and Map, and understand method overriding. This chapter focuses on how HashSet and HashMap use hashCode() and equals() together.
The lookup process
A hash-based collection stores objects in buckets. A bucket is a location chosen from an object's hash code.
When you add an object to a HashSet, Java:
- Calls
hashCode()to choose a bucket. - Stores the object in that bucket.
- Uses
equals()when it must compare the object with another object already in that bucket.
A HashMap follows the same process for keys. It uses the key's hash code to find a bucket, then uses equals() to find the matching key inside that bucket.
hashCode() narrows the search. equals() confirms the match.
Different objects can have the same hash code. This situation is called a collision. The collection handles collisions by comparing objects with equals().
| Method | Role in a hash collection |
|---|---|
| `hashCode()` | Chooses the bucket to search |
| `equals()` | Confirms which object in that bucket matches |
Why both methods must agree
The contract is:
- If
a.equals(b)istrue,a.hashCode()must equalb.hashCode(). - If two hash codes are equal, the objects do not have to be equal.
The second rule allows collisions. The first rule is required for reliable lookup.
Suppose a class overrides equals() but inherits Object.hashCode(). Two logically equal objects can then produce different identity-based hash codes. They go into different buckets, so a lookup may never call equals().
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
final class UserId {
private final String value;
UserId(String value) {
this.value = Objects.requireNonNull(value);
}
@Override
public boolean equals(Object other) {
return other instanceof UserId
&& value.equals(((UserId) other).value);
}
@Override
public int hashCode() {
return value.hashCode();
}
}
public class HashCollectionsDemo {
public static void main(String[] args) {
Set<UserId> ids = new HashSet<>();
ids.add(new UserId("A-17"));
System.out.println(ids.contains(new UserId("A-17"))); // true
System.out.println(ids.contains(new UserId("B-42"))); // false
}
}The two UserId objects containing "A-17" are different objects, but they are equal by value. Their equal values also produce equal hash codes, so the set searches the correct bucket and then confirms equality.
The same rule affects replacement in a HashMap. If a new key is equal to an existing key and has the same hash code, put updates the existing entry instead of creating a logically duplicate key.
A practical checklist
When a class will be used as a key or set element:
- Base both methods on the same identity fields.
- Use immutable fields when possible.
- Keep
hashCode()consistent while the object is stored. - Remember that equal objects need equal hash codes, but unequal objects may share a hash code.
Exercise
A HashSet contains an object a. A new object b satisfies a.equals(b), but their hash codes differ. What can happen when calling set.contains(b)?
Show answer
The set can search a different bucket and return false without calling equals() on a. The class violates the hash code contract.