{"id":971,"date":"2026-11-09T13:44:00","date_gmt":"2026-11-09T12:44:00","guid":{"rendered":"https:\/\/grindloop.ai\/blog\/?p=971"},"modified":"2026-11-09T09:49:24","modified_gmt":"2026-11-09T08:49:24","slug":"kotlin-hashset-contains-returns-false","status":"publish","type":"post","link":"https:\/\/grindloop.ai\/blog\/kotlin-hashset-contains-returns-false\/","title":{"rendered":"Kotlin HashSet contains() Returns False After Changing a Data Class var"},"content":{"rendered":"<p>If a Kotlin HashSet contains returns false for an object you just added, that object usually changed. A data class builds <code>hashCode()<\/code> from every property in its primary constructor, including each <code>var<\/code>. The set files the object under the hash it had when you added it. Change a <code>var<\/code> and the object now hashes somewhere else. So <code>contains<\/code> looks in the wrong place and returns false. <code>remove<\/code> does the same and returns false. A second cause makes this easy to miss. The set and the screen&#8217;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 &#8220;1 selected&#8221; 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 <code>copy()<\/code> instead of mutating them.<\/p>\n\n<h2>HashSet contains returns false and the same photo gets selected twice<\/h2>\n\n<p>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.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">data class Photo(val id: Long, var caption: String, var isFavorite: Boolean)\n\nclass GalleryViewModel {\n    val photos = listOf(\n        Photo(7, \"Beach\", false),\n        Photo(8, \"Dinner\", false),\n    )\n    val selected = mutableSetOf&lt;Photo&gt;()\n\n    fun toggleSelect(photo: Photo) {\n        if (photo in selected) selected.remove(photo) else selected.add(photo)\n    }\n\n    fun toggleFavorite(photo: Photo) {\n        photo.isFavorite = !photo.isFavorite\n    }\n}<\/pre>\n\n\n<p>The user selects the beach photo, stars it, then taps its checkbox again. We drove that sequence from a small <code>main<\/code>. It was compiled with Kotlin 2.4.20 and run on OpenJDK 25.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">set class: LinkedHashSet\nafter select: size=1 checked=true\nafter favorite: size=1 checked=false\nremove(beach) returns false\nany { it == beach } = true\nafter tapping the checkbox again: size=2 checked=true\ncontents: [Photo(id=7, caption=Beach, isFavorite=true), Photo(id=7, caption=Beach, isFavorite=true)]<\/pre>\n\n\n<p>Starring the photo unchecks it. Yet the set still holds one element. <code>remove<\/code> can&#8217;t find it. A linear scan with <code>any<\/code> 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 &#8220;Share 2 photos&#8221; button would share one photo twice. Nothing throws, so no crash report points here.<\/p>\n\n<h2>The data class hashes its var isFavorite flag<\/h2>\n\n<p>The compiler derives <code>equals()<\/code> and <code>hashCode()<\/code> from every primary constructor property. The <a href=\"https:\/\/kotlinlang.org\/docs\/data-classes.html\" target=\"_blank\" rel=\"noopener\">Kotlin data classes page<\/a> says so. It doesn&#8217;t skip a <code>var<\/code>. So <code>isFavorite<\/code> is part of the photo&#8217;s identity as far as any hash-based collection can tell. Flip it and <code>hashCode()<\/code> returns a new value.<\/p>\n\n<p>The same page gives the one exclusion. A property declared in the class body is left out of the generated functions. Our <code>Photo<\/code> has no such property. Every field, including the UI flag, feeds the hash.<\/p>\n\n<p>That alone isn&#8217;t a bug. A data class with a <code>var<\/code> works fine in a <code>List<\/code>. A list compares each element with <code>equals<\/code>. The trouble starts when the object is a key in a hash table.<\/p>\n\n<h2>The list and the set share one Photo instance, so the key changes in place<\/h2>\n\n<p><code>toggleSelect<\/code> adds the exact object from <code>photos<\/code>. It doesn&#8217;t add a copy. So <code>toggleFavorite<\/code> writes to the same object the set is holding. The set never hears about it.<\/p>\n\n<p>The <a href=\"https:\/\/developer.android.com\/reference\/java\/util\/Set\" target=\"_blank\" rel=\"noopener\">Android reference for <code>java.util.Set<\/code><\/a> warns about this case. It says a set&#8217;s behavior isn&#8217;t specified when an element changes in a way that affects <code>equals<\/code>. <code>mutableSetOf()<\/code> gave us a <code>LinkedHashSet<\/code> in the run above. The <a href=\"https:\/\/developer.android.com\/reference\/java\/util\/HashSet\" target=\"_blank\" rel=\"noopener\"><code>HashSet<\/code> reference<\/a> says it&#8217;s backed by a <code>HashMap<\/code>.<\/p>\n\n<p>We traced the lookup in <a href=\"https:\/\/raw.githubusercontent.com\/openjdk\/jdk\/master\/src\/java.base\/share\/classes\/java\/util\/HashMap.java\" target=\"_blank\" rel=\"noopener\">OpenJDK&#8217;s <code>HashMap<\/code> source<\/a>. <code>getNode<\/code> computes the bucket from the key&#8217;s current hash. It then compares that hash with the hash stored on each node. Only after a hash match does it call <code>equals<\/code>. 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&#8217;t match.<\/p>\n\n<p>That explains every line of the output. <code>contains<\/code> and <code>remove<\/code> both go through the hash, so both miss. <code>any<\/code> walks the elements and calls <code>equals<\/code>, so it finds the photo. <code>add<\/code> also checks by hash first. It finds no match, so it stores a second node for the same object.<\/p>\n\n<p>The two causes need each other. With all <code>val<\/code> properties, the hash can&#8217;t change. With a defensive copy in the set, the list edit can&#8217;t reach the key. This code has neither.<\/p>\n\n<h2>Select by stable ID and replace photos with copy()<\/h2>\n\n<p>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.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"kotlin\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">data class Photo(val id: Long, val caption: String, val isFavorite: Boolean)\n\ndata class GalleryState(\n    val photos: List&lt;Photo&gt; = emptyList(),\n    val selectedIds: Set&lt;Long&gt; = emptySet(),\n)\n\nclass GalleryViewModel {\n    var state = GalleryState(\n        photos = listOf(Photo(7, \"Beach\", false), Photo(8, \"Dinner\", false)),\n    )\n        private set\n\n    fun toggleSelect(id: Long) {\n        val ids = state.selectedIds\n        state = state.copy(selectedIds = if (id in ids) ids - id else ids + id)\n    }\n\n    fun toggleFavorite(id: Long) {\n        state = state.copy(\n            photos = state.photos.map { if (it.id == id) it.copy(isFavorite = !it.isFavorite) else it },\n        )\n    }\n}<\/pre>\n\n\n<p>The same select, star and deselect sequence now behaves.<\/p>\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">after select: size=1 checked=true\nafter favorite: size=1 checked=true favorite=true\nafter deselect: size=0 checked=false<\/pre>\n\n\n<p>A <code>Long<\/code> can&#8217;t change after it goes into the set. The favorite flag can change as often as the user likes. In a real app, <code>state<\/code> would be a <code>MutableStateFlow<\/code> updated with <code>update {}<\/code>. Replacing the whole state also gives observers a new value to react to. Shared mutable objects inside state cause a related bug. See <a href=\"https:\/\/grindloop.ai\/blog\/stateflow-not-emitting-mutablelist\/\">StateFlow not emitting after a MutableList add<\/a>.<\/p>\n\n<p>Sometimes the set has to hold whole objects, for example a cache keyed by the item. Then base <code>equals<\/code> and <code>hashCode<\/code> 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 <a href=\"https:\/\/grindloop.ai\/blog\/kotlin-data-class-equals-ignores-parent-class\/\">why a data class equals() ignores the parent class<\/a>.<\/p>\n\n<h2>Walk the interviewer from the unchecked box to both causes<\/h2>\n\n<p>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.<\/p>\n\n<ol>\n<li>Reproduce it. Select, star, then check <code>photo in selected<\/code>. It&#8217;s false while <code>selected.size<\/code> is 1.<\/li>\n<li>Rule out <code>equals<\/code>. <code>selected.any { it == photo }<\/code> is true, so equality still holds. The hash lookup is what fails.<\/li>\n<li>Name the first cause. The data class hashes every constructor property, so the <code>var isFavorite<\/code> changes the hash.<\/li>\n<li>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.<\/li>\n<li>Explain the duplicate. <code>add<\/code> also misses the old entry, so a second tap stores a second node.<\/li>\n<li>Give the fix. Store <code>Set&lt;Long&gt;<\/code> of IDs and make <code>Photo<\/code> immutable with <code>copy()<\/code> for edits.<\/li>\n<\/ol>\n\n<p>A debugging round often hides more than one bug. Hass covers how it&#8217;s scored past the first fix in <a href=\"https:\/\/grindloop.ai\/blog\/android-debugging-interview-second-bug\/\">finding the bug and still not passing<\/a>.<\/p>\n\n<h2>Wrong answers that leave the set corrupted<\/h2>\n\n<ul>\n<li>&#8220;<code>equals<\/code> is broken.&#8221; It isn&#8217;t. The two entries in the output are the same object. Its hash moved.<\/li>\n<li>&#8220;Use <code>removeAll { it.id == id }<\/code>.&#8221; It did clear both entries in our run. OpenJDK&#8217;s iterator removes each node by its stored hash, so it works. But <code>contains<\/code> still lies until then. The next favorite toggle corrupts the set again.<\/li>\n<li>&#8220;Remove the photo, change it, then add it back.&#8221; That works only if every writer remembers to do it. A second screen that edits the photo breaks it again.<\/li>\n<li>&#8220;Switch to <code>HashSet<\/code> or <code>LinkedHashSet<\/code>.&#8221; Both are hash tables, so both fail the same way. Only the iteration order differs.<\/li>\n<li>&#8220;Mark the properties <code>val<\/code> and keep the set of photos.&#8221; That stops the corruption. But a starred photo is now a new object that isn&#8217;t equal to the selected one. Selection is lost on every favorite tap. Key the set by ID.<\/li>\n<\/ul>","protected":false},"excerpt":{"rendered":"<p>HashSet contains returns false after a data class var changes, because the hash moved. A runnable repro, the ID-set fix and the interview answer.<\/p>\n","protected":false},"author":2,"featured_media":974,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"Kotlin HashSet contains() Returns False After Changing a Data Class var","rank_math_description":"HashSet contains returns false after a data class var changes, because the hash moved. A runnable repro, the ID-set fix and the interview answer.","rank_math_focus_keyword":"hashset contains returns false","footnotes":""},"categories":[9,2],"tags":[15,65,87,66,16,91,12,45],"class_list":["post-971","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bug-squash","category-kotlin","tag-android","tag-data-class","tag-debugging-interview","tag-equals-hashcode","tag-interview-prep","tag-java-collections","tag-kotlin","tag-technical-interview"],"_links":{"self":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/971","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/comments?post=971"}],"version-history":[{"count":2,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/971\/revisions"}],"predecessor-version":[{"id":973,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/posts\/971\/revisions\/973"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media\/974"}],"wp:attachment":[{"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/media?parent=971"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/categories?post=971"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/grindloop.ai\/blog\/wp-json\/wp\/v2\/tags?post=971"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}