gpt4 book ai didi

Scala 相等性和哈希码

转载 作者:行者123 更新时间:2023-12-01 10:13:45 24 4
gpt4 key购买 nike

Scala in Depth可变性相等性 上呈现此代码。

class Point2(var x: Int, var y: Int) extends Equals {
def move(mx: Int, my: Int) : Unit = {
x = x + mx
y = y + my
}
override def hashCode(): Int = y + (31*x)

def canEqual(that: Any): Boolean = that match {
case p: Point2 => true
case _ => false
}
override def equals(that: Any): Boolean = {
def strictEquals(other: Point2) =
this.x == other.x && this.y == other.y
that match {
case a: AnyRef if this eq a => true
case p: Point2 => (p canEqual this) && strictEquals(p)
case _ => false
}
}
}

然后,它执行评估。

scala> val x = new Point2(1,1)
x: Point2 = Point2@20
scala> val y = new Point2(1,2)
y: Point2 = Point2@21
scala> val z = new Point2(1,1)
z: Point2 = Point2@20

接下来,创建一个HashMap

scala> val map = HashMap(x -> "HAI", y -> "WORLD")
map: scala.collection.immutable.HashMap[Point2,java.lang.String] =
Map((Point2@21,WORLD), (Point2@20,HAI))

scala> x.move(1,1)

scala> map(y)
res9: java.lang.String = WORLD

我知道 map(x) 将返回 NoSuchElementException,因为 x 已发生变异。由于 x.move(1,1) 的突变,x 的 hashCode 被重新计算。因此,当检查 x 是否在 map 中时,map 的 hashCode 都不匹配 x新的 hashCode

scala> map(x)
java.util.NoSuchElementException: key not found: Point2@40
...

由于z等于(值)HashMap的最初插入的x,以及hashCode,为什么抛出异常?

scala> map(z)
java.util.NoSuchElementException: key not found: Point2@20

编辑 在我看来,这个例子显示了命令式编程的复杂性(坏)。

最佳答案

因为 map 仍然使用x测试是否相等。

这是发生了什么:

  • 您使用 x 在 map 中插入作为key,此时的hashCode为#x。太好了。
  • 您更改了 x 上的一些值, #x 现在不见了,新的 hashCode 是 #x'。
  • 您尝试查找与 x 关联的值在 map 上。 map 获取哈希代码:#x'。它不存在于 map 中(因为在插入时它是#x)。
  • 你创造了z具有相同的值 x本来就有。
  • 您查找与 z 关联的值.该 map 找到了 z 的 hashCode 值(因为它是#x),然后调用 equalszx (您在第一步中用于插入值的同一实例)。你得到 false自从你搬家后x !

映射保持对键实例的引用,并用它来测试equals当你get ,但它从不重新计算 hashCode。

关于Scala 相等性和哈希码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20642861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com