If a Kotlin HashSet contains returns false for an object you just added, that object usually changed. A data class builds hashCode() from every property in its primary constructor, including each var. The set files the object under the hash it had when you added it. Change a var and the object now hashes somewhere else. So contains looks in the wrong place and returns false. remove does the same and returns false. A second cause makes this easy to miss. The set and the screen’s list hold the same instance. So a harmless edit on the list item changes the key inside the set. Marking a photo as a favorite is enough. On a selection screen this shows up as an unchecked box with “1 selected” in the toolbar. One more tap adds the same photo twice. The fix is to store stable IDs in the set. Then replace items with copy() instead of mutating them.
HashSet contains returns false and the same photo gets selected twice
A gallery screen lets the user select photos for sharing. Each photo can also be starred as a favorite. The ViewModel keeps the photos in a list and the selection in a set.
data class Photo(val id: Long, var caption: String, var isFavorite: Boolean)
class GalleryViewModel {
val photos = listOf(
Photo(7, "Beach", false),
Photo(8, "Dinner", false),
)
val selected = mutableSetOf<Photo>()
fun toggleSelect(photo: Photo) {
if (photo in selected) selected.remove(photo) else selected.add(photo)
}
fun toggleFavorite(photo: Photo) {
photo.isFavorite = !photo.isFavorite
}
}
The user selects the beach photo, stars it, then taps its checkbox again. We drove that sequence from a small main. It was compiled with Kotlin 2.4.20 and run on OpenJDK 25.
set class: LinkedHashSet
after select: size=1 checked=true
after favorite: size=1 checked=false
remove(beach) returns false
any { it == beach } = true
after tapping the checkbox again: size=2 checked=true
contents: [Photo(id=7, caption=Beach, isFavorite=true), Photo(id=7, caption=Beach, isFavorite=true)]
Starring the photo unchecks it. Yet the set still holds one element. remove can’t find it. A linear scan with any finds it at once. Then the next tap adds the photo again. The set now holds two elements that are equal to each other. A “Share 2 photos” button would share one photo twice. Nothing throws, so no crash report points here.
The data class hashes its var isFavorite flag
The compiler derives equals() and hashCode() from every primary constructor property. The Kotlin data classes page says so. It doesn’t skip a var. So isFavorite is part of the photo’s identity as far as any hash-based collection can tell. Flip it and hashCode() returns a new value.
The same page gives the one exclusion. A property declared in the class body is left out of the generated functions. Our Photo has no such property. Every field, including the UI flag, feeds the hash.
That alone isn’t a bug. A data class with a var works fine in a List. A list compares each element with equals. The trouble starts when the object is a key in a hash table.
The list and the set share one Photo instance, so the key changes in place
toggleSelect adds the exact object from photos. It doesn’t add a copy. So toggleFavorite writes to the same object the set is holding. The set never hears about it.
The Android reference for java.util.Set warns about this case. It says a set’s behavior isn’t specified when an element changes in a way that affects equals. mutableSetOf() gave us a LinkedHashSet in the run above. The HashSet reference says it’s backed by a HashMap.
We traced the lookup in OpenJDK’s HashMap source. getNode computes the bucket from the key’s current hash. It then compares that hash with the hash stored on each node. Only after a hash match does it call equals. Our photo sits in the bucket for its old hash, with the old hash stored on its node. A lookup with the new hash checks a different bucket. Even a lucky bucket collision fails, because the stored hash doesn’t match.
That explains every line of the output. contains and remove both go through the hash, so both miss. any walks the elements and calls equals, so it finds the photo. add also checks by hash first. It finds no match, so it stores a second node for the same object.
The two causes need each other. With all val properties, the hash can’t change. With a defensive copy in the set, the list edit can’t reach the key. This code has neither.
Select by stable ID and replace photos with copy()
Selection tracks which photo the user picked. So the set should hold the one value that never changes, the ID. The photo itself becomes immutable. A favorite toggle replaces the photo with a copy.
data class Photo(val id: Long, val caption: String, val isFavorite: Boolean)
data class GalleryState(
val photos: List<Photo> = emptyList(),
val selectedIds: Set<Long> = emptySet(),
)
class GalleryViewModel {
var state = GalleryState(
photos = listOf(Photo(7, "Beach", false), Photo(8, "Dinner", false)),
)
private set
fun toggleSelect(id: Long) {
val ids = state.selectedIds
state = state.copy(selectedIds = if (id in ids) ids - id else ids + id)
}
fun toggleFavorite(id: Long) {
state = state.copy(
photos = state.photos.map { if (it.id == id) it.copy(isFavorite = !it.isFavorite) else it },
)
}
}
The same select, star and deselect sequence now behaves.
after select: size=1 checked=true after favorite: size=1 checked=true favorite=true after deselect: size=0 checked=false
A Long can’t change after it goes into the set. The favorite flag can change as often as the user likes. In a real app, state would be a MutableStateFlow updated with update {}. Replacing the whole state also gives observers a new value to react to. Shared mutable objects inside state cause a related bug. See StateFlow not emitting after a MutableList add.
Sometimes the set has to hold whole objects, for example a cache keyed by the item. Then base equals and hashCode on the ID only, or keep the mutable fields in the class body. Write the override by hand and keep both functions in step. That override has its own hash code trap. We cover it in why a data class equals() ignores the parent class.
Walk the interviewer from the unchecked box to both causes
An interviewer may hand you only the symptom. The checkbox unchecks after a favorite tap. The share count is also too high. Work from the symptom to both causes.
- Reproduce it. Select, star, then check
photo in selected. It’s false whileselected.sizeis 1. - Rule out
equals.selected.any { it == photo }is true, so equality still holds. The hash lookup is what fails. - Name the first cause. The data class hashes every constructor property, so the
var isFavoritechanges the hash. - Name the second cause. The set holds the same instance as the list, so the favorite edit changed a key in place. The set still files it under the old hash.
- Explain the duplicate.
addalso misses the old entry, so a second tap stores a second node. - Give the fix. Store
Set<Long>of IDs and makePhotoimmutable withcopy()for edits.
A debugging round often hides more than one bug. Hass covers how it’s scored past the first fix in finding the bug and still not passing.
Wrong answers that leave the set corrupted
- “
equalsis broken.” It isn’t. The two entries in the output are the same object. Its hash moved. - “Use
removeAll { it.id == id }.” It did clear both entries in our run. OpenJDK’s iterator removes each node by its stored hash, so it works. Butcontainsstill lies until then. The next favorite toggle corrupts the set again. - “Remove the photo, change it, then add it back.” That works only if every writer remembers to do it. A second screen that edits the photo breaks it again.
- “Switch to
HashSetorLinkedHashSet.” Both are hash tables, so both fail the same way. Only the iteration order differs. - “Mark the properties
valand keep the set of photos.” That stops the corruption. But a starred photo is now a new object that isn’t equal to the selected one. Selection is lost on every favorite tap. Key the set by ID.