什么是合适的方法来计算一个数组的hashCode,取决于它的内容?Array.hashCode
用于数组示例:
val h = a.hashCode
println(h == Array(1,2).hashCode) // false
a(0) = 42
println(h == a.hashCode) // true
字符串
注意:最好避免在计算hashCode之前将整个数组复制到List中
为什么我问:我在类中使用Array(作为私有字段),因为查找时间很关键,并且它的内容与计算类的hashCode相关
4条答案
按热度按时间oewdyzsn1#
从https://issues.scala-lang.org/browse/SI-1607,它说数组的hashCode是java的hashCode,因为scala数组是java数组。scala不能改变它。
但它也说scala在WrappedArray中有一个合适的hashCode方法。因此:
字符串
5ssjco0h2#
你也可以使用
java.util.Arrays.hashCode(a)
,它可能比a.toSeq.hashCode
更快(因为WrappedArray
似乎继承了一个非数组特定的实现)。esbemjvw3#
您可以直接使用MurmurHash3算法。
字符串
c9x0cxw04#
使用Arrays.deepHashCode(Object[] a)。在scala中你应该使用ugly:
字符串
这种方法也适用于多维数组