Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading