Juh*_*uh_ 4 arrays scala hashcode
计算取决于其内容的 Array 的 hashCode 的合适方法是什么?
Array.hashCode
用于数组实例:
val h = a.hashCode
println(h == Array(1,2).hashCode) // false
a(0) = 42
println(h == a.hashCode) // true
Run Code Online (Sandbox Code Playgroud)
注意:在计算 hashCode 之前,最好避免将整个数组复制到例如 List
为什么我问:我在类中使用数组(作为私有字段),因为查找时间很关键,其内容与计算类的 hashCode 相关
来自https://issues.scala-lang.org/browse/SI-1607,它说 Array 的 hashCode 是来自 java 的 hashCode,因为 scala Array 是 java Array。而 Scala 无法改变它。
但它也说 Scala 在 WrappedArray 中有一个合适的 hashCode 方法。因此:
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
Run Code Online (Sandbox Code Playgroud)