相等是否意味着哈希值相等?
Should equality imply equal hash values?
我目前正在研究图形数据类型,在这种情况下,我对有关身份和平等的语义问题进行了很多思考。
我现在的情况如下。我有一个 Vertex
类型:
final class Vertex<T>: Hashable {
static func ==(lhs: Vertex, rhs: Vertex) -> Bool {
return lhs === rhs
}
var value: T
var hashValue: Int {
return ObjectIdentifier(self).hashValue
}
}
如你所见,平等是由身份决定的。我这样做是出于特定于图形数据类型的原因,但它基本上可以归结为这样一个事实,即顶点应该根据它们的身份来查看,因此只有在它们相同时才被视为相等 (相同) 顶点.
现在哈希值也由身份决定(使用ObjectIdentifier
)。这似乎是获取散列值的最简单方法,而且似乎也符合这种类型的平等概念。
但这让我开始思考...
通过 value
属性(如果 T
符合 Hashable
).
在那种情况下,两个 Vertex
可以始终具有相等的哈希值(不仅仅是程序的一次调用),而不被认为是相等的。这似乎不对。
那么反过来:说实例相等应该意味着它们的哈希值相等是否明智?
来自 Hashable
的文档:
"A hash value, provided by a type’s hashValue property, is an integer that is the same for any two instances that compare equally. That is, for two instances a and b of the same type, if a == b then a.hashValue == b.hashValue. The reverse is not true: Two instances with equal hash values are not necessarily equal to each other."
换句话说,如果 ==
return 和 true
,hashValue
必须 return 两个对象的值相同。
散列的要求是,如果两个值 a
和 b
相同,则 a.hashvalue == b.hashvalue
。然而,这并不意味着反之亦然。如果两个散列值相同,则散列项可能不相同。所以当你这么说时
- "equality of instances should imply equality of their hash values?"这实际上是一个要求。
- "two Vertexs could have equal hash values consistently (not just for one invocation of the program), without being considered equal. And that doesn't seem right" - 事实上这是可能的。
我目前正在研究图形数据类型,在这种情况下,我对有关身份和平等的语义问题进行了很多思考。
我现在的情况如下。我有一个 Vertex
类型:
final class Vertex<T>: Hashable {
static func ==(lhs: Vertex, rhs: Vertex) -> Bool {
return lhs === rhs
}
var value: T
var hashValue: Int {
return ObjectIdentifier(self).hashValue
}
}
如你所见,平等是由身份决定的。我这样做是出于特定于图形数据类型的原因,但它基本上可以归结为这样一个事实,即顶点应该根据它们的身份来查看,因此只有在它们相同时才被视为相等 (相同) 顶点.
现在哈希值也由身份决定(使用ObjectIdentifier
)。这似乎是获取散列值的最简单方法,而且似乎也符合这种类型的平等概念。
但这让我开始思考...
通过 value
属性(如果 T
符合 Hashable
).
在那种情况下,两个 Vertex
可以始终具有相等的哈希值(不仅仅是程序的一次调用),而不被认为是相等的。这似乎不对。
那么反过来:说实例相等应该意味着它们的哈希值相等是否明智?
来自 Hashable
的文档:
"A hash value, provided by a type’s hashValue property, is an integer that is the same for any two instances that compare equally. That is, for two instances a and b of the same type, if a == b then a.hashValue == b.hashValue. The reverse is not true: Two instances with equal hash values are not necessarily equal to each other."
换句话说,如果 ==
return 和 true
,hashValue
必须 return 两个对象的值相同。
散列的要求是,如果两个值 a
和 b
相同,则 a.hashvalue == b.hashvalue
。然而,这并不意味着反之亦然。如果两个散列值相同,则散列项可能不相同。所以当你这么说时
- "equality of instances should imply equality of their hash values?"这实际上是一个要求。
- "two Vertexs could have equal hash values consistently (not just for one invocation of the program), without being considered equal. And that doesn't seem right" - 事实上这是可能的。