Search code examples
javakotlinhashmapkeyequals

How to force object equivalence for keys in a Kotlin hashmap?


I have a class 'Foo' (not under my control) which I wish to use as a key in a kotlin (java) hashmap. The problem is that the 'equals' method for 'Foo' does value equivalence. For my situation value equivalence is too loose. I need object equivalence.

What are the ways to force force the use of object equivalence on the keys?

I am thinking something like...

data class Foo(val prop: String)
data class Bar(val prop: String)

fun main() {
    val fooMap = mutableMapOf<Any, Bar>()

    val fooA = Foo("common value")
    val fooB = Foo("common value")

    fooMap[fooA] = Bar("different A")
    fooMap[fooB] = Bar("different B")
    println("${fooMap.keys} ${fooMap.values}")
}

This results in a fooMap with only one entry, when I expect two.

[Foo(prop=common value)] [Bar(prop=different B)]

Solution

  • Consider using IdentityHashMap - it is the same map, but which compares only references of the keys.

    Also note, to effectively use regular HashMap, the key class must respect not only equals, but also hashCode.