Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 542
Juh_ Avatar asked Dec 14 '22 02:12

Juh_


2 Answers

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
like image 147
Juh_ Avatar answered Dec 21 '22 12:12

Juh_


You can also use java.util.Arrays.hashCode(a), it's likely to be faster than a.toSeq.hashCode (since WrappedArray seems to inherit a non-array-specific implementation).

like image 25
Alexey Romanov Avatar answered Dec 21 '22 10:12

Alexey Romanov