Hashmap.containsKey with array as key doesn't work

Viewed 22
fun main(args: Array<String>) {
        var map= HashMap<IntArray, Boolean> ()
        map.put(intArrayOf(1,2,3,4),true)
        map.put(intArrayOf(2),true)
        map.put(intArrayOf(3),false)
        if (map.containsKey(intArrayOf(3))) println("hello, i'm here")

}

I have some line of code in kotlin. it's seem like i need to modifie the comparator of method containsKey(). Can some one show me how. Thank you

1 Answers

Kotlin arrays do not override equals or hashCode (which is what HashMap uses), Therefore, the implementation from Any is inherited, and equals compares reference equality.

Alternatives I can think of:

  • TreeMap with a custom comparer

      TreeMap<IntArray, Boolean>(Arrays::compare)
    

    Unlike equals, Arrays.compare actually compares the contents of the array, and we are using that as the comparer for the TreeMap, which is a map implementation that allows us to specify a custom comparer. Do note that this has worse asymptotic performance (logarithmic vs constant time) compared to HashMap, and that it is JVM-only.

    You should also make sure not to modify the arrays once they are put inside the map, as this can lead to unspecified behaviour.

  • HashMap<List<Int>, Boolean>

    Change the keys to lists, which do override equals and hashCode. This has the additional advantage of making the keys immutable, so you won't accidentally change the keys once they are in the map and cause unspecified things to happen.

Related