Search code examples
arraysscalahashcode

How to get a correct array hashcode in scala?


What is the suitable way to compute hashCode of an Array that depends on its content?

Array.hashCode is for the array instance:

val h = a.hashCode
println(h == Array(1,2).hashCode) // false

a(0) = 42
println(h == a.hashCode) // true

Note: It'd be better to avoid copying the whole array, to a List for example, prior to computing the hashCode

Why I ask: I use an Array in a class (as a private field) because lookup time is critical, and its content is relevant to compute the hashCode of the class


Solution

  • from https://issues.scala-lang.org/browse/SI-1607, it says that the hashCode of Array is the hashCode from java, as scala Array are java Array. And scala could not changed it.

    But it also says that scala has a suitable hashCode method in WrappedArray. Thus:

    val a = Array(1,2)
    val h = a.toSeq.hashCode // wrapped it in a WrappedArray - no copy
    println(h == Array(1,2).toSeq.hashCode) // true
    
    a(0) = 42
    println(h == a.toSeq.hashCode) // false