Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

A User object is added to a HashSet<User>. Later the code calls user.setEmail(newEmail), and hashCode() includes email. Now set.contains(user) returns false and set.remove(user) does nothing, but iterating the set still shows the user. Explain and fix.

The user was stored in the bucket chosen by its old hash code. After setEmail() changes a field that hashCode() uses, contains() and remove() compute the new hash and look in a different bucket, and even if they land in the same one, the node still carries the old stored hash, so the comparison fails before equals() is called. Iteration walks every bucket, so the user is still visible, but nothing can find or remove it, which leaks the entry. Fields used by hashCode() and equals() must not change while an object is in a hash-based collection: use immutable keys or a stable id, or remove the object, change it and add it back.

Why this question is asked

This bug feels impossible the first time we see it: the set prints the user, yet the set says it does not contain the user. It usually appears in caches, deduplication sets and JPA collections, and it can quietly leak memory for weeks. Interviewers ask it because it tests whether we understand that a HashSet remembers where it put an object based on its hash at that moment. In this answer, we will recap how a HashSet stores objects, reproduce the bug, follow contains() step by step to see why it fails, explain why iteration still finds the user, and then fix it two ways.

1A Quick Recap: How a HashSet Stores Objects

A HashSet is a thin wrapper around a HashMap: each element is stored as a key, with a shared dummy object as the value. So everything about HashMap keys applies to HashSet elements.

When we add an element, the map calls hashCode(), mixes the bits, and picks a bucket in its internal table with (n - 1) & hash. It stores a node in that bucket holding the element and the hash it computed at that moment. The stored hash is used later as a quick filter: before calling equals() on a node, the map checks that the node's stored hash equals the hash it is looking for. The map never recomputes the hash of an element it already holds, because it has no reason to expect it to change.

2Reproducing the Bug

Java
class User {
private final long id;
private String email;
User(long id, String email) { this.id = id; this.email = email; }
void setEmail(String e) { this.email = e; }
@Override public boolean equals(Object o) {
return o instanceof User u && u.id == id && u.email.equals(email);
}
@Override public int hashCode() { return Objects.hash(id, email); }
}
Set<User> set = new HashSet<>();
User user = new User(7, "old@example.com");
set.add(user);
user.setEmail("new@example.com");
System.out.println(set.contains(user)); // false
System.out.println(set.remove(user)); // false: nothing removed
System.out.println(set.size()); // 1
for (User u : set) System.out.println(u == user); // true: it is still in there

Notice that contains() fails even though we pass the very same object that is in the set. Identity does not help, because the map does not get as far as comparing references.

3Following contains() Step by Step

contains(user) calls user.hashCode(), which now uses the new email, so it returns a different number from the one computed at add() time. The map spreads that hash and picks a bucket. With a different hash, that is almost always a different bucket, usually an empty one, so contains() returns false immediately.

Sometimes the new hash lands in the same bucket by chance, since only the low bits pick the bucket. Even then, the map checks node.hash == hash first, and the node still holds the old hash. The check fails, so the map moves on without ever testing key == user or calling equals(). remove() follows exactly the same path, so it also finds nothing and returns false.

The node in the set before and after setEmail()
Momentuser.hashCode()Node's stored hashBucket looked in
add(user)h1 (old email)h1bucket(h1): node stored here
contains(user) after setEmailh2 (new email)still h1bucket(h2): usually empty
same bucket by chanceh2still h1h1 != h2, node skipped
The set remembers where it put the object; the object no longer agrees.

4Why Iteration Still Shows the User

Iteration does not use hashes at all. The iterator walks the table from bucket 0 to the end and visits every node in every bucket. Our node is still in the bucket for the old hash, so the iterator finds it and returns the user.

This mismatch is what makes the bug a leak. The object is in the set, it counts towards size(), and it is reachable, so it is never garbage collected, but no lookup can find it and no remove() can take it out. If this happens on every update in a long-lived set or cache, the set grows forever with entries that can never be removed. Adding the user again also succeeds, so the set can end up with two nodes for the same object, which breaks deduplication too. Iterator.remove() still works, because it removes the node it is standing on, but that is a clean-up tool, not a fix.

5Fix 1: Keep Hash Fields Immutable

The rule is that fields used by hashCode() and equals() must not change while the object is a key in a hash-based collection. The simplest way to guarantee that is to base equality only on fields that never change. For a user, that is the stable id.

Java
class User {
private final long id; // never changes
private String email; // may change freely
@Override public boolean equals(Object o) { return o instanceof User u && u.id == id; }
@Override public int hashCode() { return Long.hashCode(id); }
}
set.add(user);
user.setEmail("new@example.com");
System.out.println(set.contains(user)); // true

For value-like keys, a record with final components is even better, because it cannot change at all. If two users with the same id but different emails must be treated as different, the email is part of the identity, and then the object should be immutable and an update should create a new User.

6Fix 2: Remove, Change, Re-Insert

When we cannot change the class, we take the object out of every hash-based collection before changing it, and put it back afterwards.

Java
set.remove(user); // found: the hash still matches the stored one
user.setEmail("new@example.com");
set.add(user); // stored under the new hash
System.out.println(set.contains(user)); // true

This works but is fragile: every caller that changes the email must know about every set the user is in. That is why the first fix is preferred, and this one is best kept for a single, well-encapsulated place, such as an update method on the class that owns the set.

7Follow-up questions

How does the same bug show up in a TreeSet?

A TreeSet does not hash; it keeps elements in a red-black tree ordered by compareTo or a comparator. If the comparator uses email and we change the email, the element is now in the wrong position in the tree. contains() follows the comparison path for the new value, goes left or right based on it, and usually misses the element, so it returns false and remove() fails, just like the HashSet. Worse, the tree's ordering invariant is broken, so searches for other elements that pass through that node can also go the wrong way, and ordered operations such as first() or headSet() can return wrong results.

Why doesn't HashSet just recompute hashes on lookup?

Because it would have to recompute the hash of every element to find a changed one, which is a full scan and defeats the purpose of hashing. The stored hash exists precisely so that lookups are O(1) and resizes do not call hashCode() again. The collection relies on keys honouring the contract instead.

Does this apply to HashMap values?

No. Only keys are located by hash. A value object can change freely while it is in a map; only the key's hashCode() and equals() must stay stable.

8Conclusion

In this answer, we saw that a HashSet, backed by a HashMap, stores each element in the bucket chosen by its hash at insertion time and keeps that hash in the node. After setEmail() changes a field used by hashCode(), contains() and remove() look in the bucket for the new hash, and even in the same bucket the stored hash no longer matches, so neither finds the user. Iteration walks every bucket, so the user is still visible but cannot be removed, which leaks the entry. The fix is to keep the fields used by hashCode() and equals() immutable, using a stable id or a record, or to remove the object, change it and re-insert it.

What to say in the interviewAbout 100 seconds aloud

Open with

HashSet is backed by a HashMap, so when I add the user, the map computes its hashCode at that moment, picks a bucket from it, and stores a node holding the user and that hash.

Then, if they want more

The map never recomputes it. When setEmail changes a field that hashCode uses, the object's hash changes but the node stays in the old bucket with the old stored hash. Now contains computes the new hash and looks in the bucket for that hash, which is usually a different, empty bucket, so it returns false.

Even if it lands in the same bucket by chance, the map compares the stored hash before it checks identity or calls equals, and the stored hash is the old one, so the node is skipped. remove follows the same lookup path, so it fails too.

Iteration is different: it just walks every bucket in the table, so it still finds the user. That combination means the entry is stuck: it counts in size, it is reachable, but nothing can remove it, so it is a memory leak, and adding the user again can even create a duplicate.

The rule is that fields used by hashCode and equals must not change while the object is a key. My preferred fix is to base equality on something immutable, like the user's id, or use a record for value types.

If I cannot change the class, I remove the user from the set, change the email, and add it back, ideally inside one method so callers cannot forget.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A User object is added to a HashSet<User>. Later the code calls user.setEmail(newEmail)...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/819c489b29/