Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

Objects are added to a HashSet, then one of their fields used in hashCode is changed. Later contains returns false and remove does nothing, but iteration shows the object. Explain.

A HashSet puts each element in a bucket chosen from its hash code at the moment it is added, and it never moves the element when its fields change. After the change, contains and remove compute the new hash code and search a different bucket, so they cannot find the element, while iteration, which walks every bucket, still shows it. The object is effectively leaked and the set can even hold the same logical element twice. The rule is that fields used by hashCode must not change while an object is in a hash-based collection.

Why this question is asked

This bug is confusing because every individual operation seems to work: the object was added, it is visibly there when we print the set, and yet the set says it does not contain it. Interviewers ask about it because the explanation requires a real picture of how a hash table stores elements, and because the same mistake appears in a very common form with JPA entities. In this answer, we will reproduce the problem, follow the element through the set's buckets to see why lookups miss it, look at the consequences, and finish with the rules that prevent it, including how to write equals and hashCode for JPA entities.

1Reproducing the Problem

Here is a small mutable class whose equals and hashCode use its name field.

Java
class Tag {
String name;
Tag(String name) { this.name = name; }
@Override public boolean equals(Object o) { return o instanceof Tag t && name.equals(t.name); }
@Override public int hashCode() { return name.hashCode(); }
@Override public String toString() { return "Tag(" + name + ")"; }
}
Set<Tag> tags = new HashSet<>();
Tag t = new Tag("java");
tags.add(t);
t.name = "kotlin"; // change a field used by hashCode
tags.contains(t); // false
tags.remove(t); // false: nothing removed
System.out.println(tags); // [Tag(kotlin)]
tags.add(t); // true
tags.size(); // 2: the same object, stored twice

Notice the last two lines. The set not only fails to find t, it accepts the very same object a second time. Each of these results follows directly from how a HashSet, which is a HashMap underneath, stores its elements.

2Why Lookups Search the Wrong Bucket

When we call add, the set computes t.hashCode() and uses it to choose a bucket, one slot of its internal array. It stores a node there that remembers both the element and its hash. That choice is made once. The set does not know that t is mutable, and it has no way to be told that t has changed.

When we later call contains(t), the set computes t.hashCode() again. The name is now "kotlin", so the hash is different, and it points to a different bucket. That bucket is empty, or holds unrelated elements, so contains returns false without ever reaching the node that holds t. remove does the same search and finds nothing to remove. Even if the new hash happened to choose the same bucket, the node's stored hash would not match the new one, so the set would still skip it.

Step throughAn element that changed while in a HashSet
CallerHashSetBucket 3Bucket 9
add(t) with name java: hash picks bucket 3
store node(hash of java, t)
t.name = kotlin: the set is not told
contains(t): hash of kotlin picks bucket 9
search bucket 9
no node found
false
iterate
walk every bucket: finds t in bucket 3
[Tag(kotlin)]

10 messages in order. Play them, or step through them one at a time.

The node stays where the old hash put it; lookups go where the new hash points.

Iteration is different. The iterator walks every bucket in order and returns whatever nodes it finds, without computing any hash codes. So printing the set shows t, in the bucket where it was originally placed.

3What This Does to the Program

The consequences go beyond one wrong answer. The element is now leaked: remove cannot reach it, so a set used as a registry or cache keeps it, and everything it references, for as long as the set lives. Long-running services that track sessions or subscriptions this way can grow without limit.

The set can also hold logical duplicates. As we saw, adding t again stores a second node in the new bucket, and adding a fresh Tag("kotlin") would too. Code that relies on a set for uniqueness, such as deduplicating events, silently stops deduplicating. One way out exists: the iterator's remove, and removeIf, which uses it, remove the node they are standing on using its stored hash, so tags.removeIf(x -> x == t) does remove it. That is a recovery tool, not a design.

4The Rule: Keys Must Not Change While Stored

The fix is to make sure the fields used by hashCode, and by equals, never change while the object is a key in a HashMap or an element of a HashSet. The best way is immutability: a record, or a final class with final fields, cannot change at all. If the class must be mutable, we remove the object, change it, and add it back, so the set rehashes it.

Java
record Tag(String name) {} // immutable: the hash can never change
// For a mutable class that must stay mutable:
tags.remove(t);
t.name = "kotlin";
tags.add(t); // placed in the right bucket again

Notice that the same rule applies to TreeSet and TreeMap with fields used in compareTo, and to keys of HashMap. Any collection that files an element by a value computed from its fields assumes that value stays the same.

5The JPA Version of the Same Bug

JPA entities often hit this without anyone changing a field by hand. If an entity's equals and hashCode use its database-generated ID, the ID is null when the entity is created and assigned only when it is persisted or flushed. Adding the entity to a set before saving it files it under the hash of a null ID.

Java
@Entity
class OrderLine {
@Id @GeneratedValue Long id;
@Override public boolean equals(Object o) { return o instanceof OrderLine l && Objects.equals(id, l.id); }
@Override public int hashCode() { return Objects.hashCode(id); } // 0 while id is null
}
Set<OrderLine> lines = new HashSet<>();
OrderLine line = new OrderLine();
lines.add(line); // filed under hash 0
entityManager.persist(line); // id assigned, for example 42
lines.contains(line); // false: hash is now Long.hashCode(42)

The ID changed underneath the set, exactly like the name in our Tag example. Worse, with this equals two different unsaved lines are equal, because both IDs are null, so a set would keep only one of them. This is why entity equality needs its own rule, which the FAQ below covers.

6Follow-up questions

How should equals and hashCode be written for JPA entities?

There are two sound approaches. If the entity has a natural business key that is set at creation and never changes, such as an ISBN or an order number, base both methods on that key. If it only has a generated ID, make equals compare IDs only when the ID is not null, so two unsaved entities are never equal, and make hashCode return a constant per class, for example getClass().hashCode(), so it does not change when the ID is assigned. Because Hibernate may hand us a proxy subclass, compare types with instanceof or Hibernate's helper for the real class rather than getClass() directly, and never include lazy associations.

Doesn't a constant hashCode make the HashSet slow?

In theory every entity of that class shares a bucket, which makes lookups linear. In practice, sets of entities in one association are small, usually tens of elements, so the cost is negligible, and correctness matters more. For very large in-memory sets, we would key by a stable business key or by the ID after saving instead.

Can this happen with a HashMap value rather than a key?

No. Only keys are hashed. Values can change freely while stored; the map finds them through their keys. The rule only concerns keys of maps and elements of sets.

7Conclusion

In this answer, we saw that a HashSet files each element under the hash code it had when it was added, so changing a field used by hashCode leaves the element in the old bucket while contains and remove search the new one. Iteration still shows it, the set leaks it, and it can be added again as a duplicate. The cure is immutable keys, or removing and re-adding after a change, and for JPA entities, equality based on a stable business key or on the ID with a constant hashCode.

What to say in the interviewAbout 80 seconds aloud

Open with

A HashSet is a HashMap underneath, and when I add an element it computes the hash code once, picks a bucket from it, and stores a node there with the element and that hash.

Then, if they want more

It never moves the node later, because it has no idea the object changed. So if I then change a field used in hashCode, contains and remove compute the new hash, look in a different bucket, and find nothing, so contains is false and remove does nothing. Iteration still shows the object because the iterator walks every bucket without hashing.

The effects are a leak, since the object can no longer be removed normally, and duplicates, because adding it again stores a second node in the new bucket.

The rule is that fields used by hashCode and equals must not change while the object is in a hash-based collection, so ideally keys are immutable, like records; otherwise remove, change, and add back.

A very common real case is JPA entities whose hashCode uses a generated ID: the ID is null when the entity goes into a set and gets assigned on persist, which changes the hash. For entities I use an immutable business key, or equals on a non-null ID with a constant hashCode per class.

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 "Objects are added to a HashSet, then one of their fields used in hashCode is changed....": https://scrivio-interview-library.netlify.app/java/object-contracts/81cb3cab41/