作者:朱泊潇 | 来源:互联网 | 2023-05-21 13:39
1> Scott Chambe..:
因为ContainsKey的逻辑与此类似.
//This is a simplified model for answering the OP's question, the real one is more complex.
private List>> _buckets = //....
public bool ContainsKey(TKey key)
{
List> bucket = _buckets[key.GetHashCode() % _buckets.Length];
foreach(var item in bucket)
{
if(key.Equals(item.Key))
return true;
}
return false;
}
所有GetHashCode都会获得你的密钥进入的存储桶,它仍然必须通过该存储桶的每个成员并通过该Equals
方法找到完全匹配.这就是为什么拥有良好的哈希码很重要,桶中的项目越少,foreach
部分就越快.最佳可能的哈希码每个桶只有一个项目.
这是HashSet上包含的实际代码(Dictionary的ContainsKey非常相似,但更复杂)
private int[] m_buckets;
private Slot[] m_slots;
public bool Contains(T item) {
if (m_buckets != null) {
int hashCode = InternalGetHashCode(item);
// see note at "HashSet" level describing why "- 1" appears in for loop
for (int i = m_buckets[hashCode % m_buckets.Length] - 1; i >= 0; i = m_slots[i].next) {
if (m_slots[i].hashCode == hashCode && m_comparer.Equals(m_slots[i].value, item)) {
return true;
}
}
}
// either m_buckets is null or wasn't found
return false;
}
private int InternalGetHashCode(T item) {
if (item == null) {
return 0;
}
return m_comparer.GetHashCode(item) & Lower31BitMask;
}
internal struct Slot {
internal int hashCode; // Lower 31 bits of hash code, -1 if unused
internal T value;
internal int next; // Index of next entry, -1 if last
}