gpt4 book ai didi

ios - 具有不同属性的两个对象的哈希值相同

转载 作者:行者123 更新时间:2023-11-28 11:06:01 27 4
gpt4 key购买 nike

考虑这个结构

struct Node : Hashable {
let value : Int
let i : Int
let j : Int

init(withValue val : Int, position : (Int,Int)){
value = val
self.i = position.0
self.j = position.1
}

var hashValue: Int {
return "\(value),\(i),\(j)".hashValue
}
}

我的== 运算符

func ==(left: Node, right: Node) -> Bool {
return left.hashValue == right.hashValue
}

当我创建 2 个节点时:

let node1 = Node(withValue: 1260, position: (8,694))
let node2 = Node(withValue: 33, position: (257,286))

比较它们:

   node1 == node2   //true ???

为什么 hashValue 函数没有按预期工作?

是否应该以其他方式实现?

反问:如果是,计算这种对象的 hashValue 的正确方法是什么?

更多信息

当我调试这个时:

(lldb) po node1.hashValue
4799450060528192039

(lldb) po node2.hashValue
4799450060528192039

最佳答案

相等的散列值不保证相等的原始值。整体概念hash collisions存在就是因为这个原因:

In computer science, a collision or clash is a situation that occurs when two distinct pieces of data have the same hash value...

Collisions are unavoidable whenever members of a very large set (such as all possible person names, or all possible computer files) are mapped to a relatively short bit string.

这意味着这个==操作符的实现是错误的:

func ==(left: Node, right: Node) -> Bool {
return left.hashValue == right.hashValue
}

应该是:

func ==(left: Node, right: Node) -> Bool {
return left.value == right.value
&& left.i == right.i
&& left.j == right.j
}

关于ios - 具有不同属性的两个对象的哈希值相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37560288/

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