Does Kotlin's LinkedHashMap use reference identity or equals() in its
get()
method? I have two different objects with the same values, and an overridden equals method which returns true. But as a key to hashmap, they don't match.
j
Joffrey
01/21/2022, 9:24 PM
Have you also overridden
hashCode()
accordingly? 2 equal objects must have the same hashcode, that's the contract between both methods. Hashmaps rely on this by first checking hashcode and then using equals when searching for keys
v
v79
01/21/2022, 9:25 PM
... suddenly I feel dumb. Be right back!
v79
01/21/2022, 9:42 PM
I've been a professional Java dev for about 10 years but now I'm just a manager. Clearly I'm forgetting the basics!
😆 2
👏 1
j
Joffrey
01/21/2022, 10:11 PM
Note that if you use Kotlin's data classes, they will have autogenerated hashcode and equals based on the properties declared in the primary constructor. It's usually easier this way
v
v79
01/21/2022, 10:24 PM
Yes, absolutely, but I needed to exclude something from equality checks in this case.
j
Joffrey
01/21/2022, 11:45 PM
Then it may depend on your exact case, but just in case, you can exclude properties from the generated `equals`/`hashCode` if you declare them outside of the primary constructor (directly in the data class's body)