Duplicities in Set

I have a problem with Set as it contains two the same instances of data class, even though it should be impossible. You can see on the screen that both objects are allocated to the same place in memory.


It is filled in regular map lambda, no concurrency.

I’ve found out, that contains() function returns false, so the element is added to the Set, but when I compare both element, they are identical.



It can be fixed with this “hack” as activatedOffers is mutableSet
activatedOffers.toSet(), but I’m curious why is it happening

I’ve prepared an example project with the exact code, but I am not able to reproduce it anywhere but my Spring app.

I know it is hard to debug this way. I am willing to do a Code With Me session to debug it.

Do you maybe modify the item after placing it in the set? I see e and f props are mutable, probably for a reason. Hash maps/sets don’t work very well with mutable items/keys. hashCode() can’t change after putting an item in a set, because then map/set won’t be able to find it:

fun main() {
    val item = MyData("foo")
    val set = mutableSetOf(item)

    item.value = "bar"

    println(set.first().hashCode() == item.hashCode()) // true
    println(set.first() == item) // true
    println(item in set) // false
}

data class MyData(var value: String)

If you want to stick to the current design, I believe it should work if you generate hashCode() manually and skip mutable props.

1 Like

I actually tried custom equals() and hashCode() implementations, but I always included the vars.
Your advice helped!
Thanks a lot!