I'm studying maps with Kotlin, and decided to run this code:
fun main() {
data class KeyClass(val equals: String, val hash: Int) {
override fun equals(other: Any?): Boolean {
return this.equals == (other as KeyClass).equals
}
override fun hashCode(): Int {
return hash
}
override fun toString(): String {
return "($equals,$hash)"
}
}
// collision, since their hashes are the same but they are not equal
val a1 = KeyClass("a", 1)
val a2 = KeyClass("b", 1)
val map = HashMap<KeyClass, String>()
map[a1] = "value1"
println(map)
map[a2] = "value2"
println(map)
val map2 = mutableMapOf<KeyClass, String>()
map2[a1] = "value1"
println(map2)
map2[a2] = "value2"
println(map2)
}
which got me:
{(a,1)=value1}
{(a,1)=value1, (b,1)=value2}
{(a,1)=value1}
{(a,1)=value1, (b,1)=value2}
I thought HashMap
's collision resulted in a list. Then when I tried mutableMapOf
which is Kotlin's LinkedHashMap
, I didn't get any collision either.
questions:
- What am I missing from this simple collision example?
- What are the most common collision behaviors per
Map
implementation?