基于这个问题中公认的答案:如何在Swift中保证均衡性?
hashValue用于第一次唯一性测试。如果hashValue与另一个元素的hashValue匹配,则使用==作为备份测试。
但是,场景集后面必须为每个元素存储一个唯一的标识符。考虑一下这个例子:
struct Country {
let name: String
let capital: String
}
extension Country: Hashable {
static func == (lhs: Country, rhs: Country) -> Bool {
return lhs.name == rhs.name && lhs.capital == rhs.capital
}
var hashValue: Int {
return name.hashValue ^ capital.hashValue
}
}
let singapore = Country(name: "Singapore", capital: "Singapore")
let monaco = Country(name: "Monaco", capital: "Monaco")
singapore.hashValue // returns 0
monaco.hashValue // returns 0
var countries: Set<Country> = []
countries.insert(singapore)
countries.insert(monaco)
countries // Contains both singapore and monaco正如你所看到的,一些国家的名字和首都的名字是一样的。这将产生hashValue碰撞。该集合将运行更昂贵的==来确定其唯一性,这可能不是O(1)。但是,在进行此比较之后,Set必须为该元素生成唯一标识符,以便存储在场景后面。
的问题:如何为这样的碰撞元素生成唯一标识符?
发布于 2017-08-11 09:34:04
哈希值似乎仅用于标识要在内部插入元素的桶(散列未存储),但使用==来比较是否使用该元素。如果集合存储增加,还需要重新散列所有元素。
您可以在讨论这里中获得更多信息。
https://stackoverflow.com/questions/45629918
复制相似问题