计算取决于其内容的数组的 hashCode 的合适方法是什么?
Array.hashCode
用于数组实例:
val h = a.hashCode
println(h == Array(1,2).hashCode) // false
a(0) = 42
println(h == a.hashCode) // true
注意:在计算 hashCode 之前,最好避免复制整个数组,例如复制到 List
为什么我问:我在类中使用数组(作为私有(private)字段),因为查找时间很关键,并且其内容与计算类的 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
关于arrays - 如何在scala中获得正确的数组哈希码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40678964/