我提供了一种替代方案,演示了一个字典在添加具有不同键但哈希码相同的两个项时将表现出无异常且功能上正确的行为。
在 .Net 4.6 中,字符串 "699391" 和 "1241308" 产生相同的哈希码。下面的代码会发生什么?
myDictionary.Add( "699391", "abc" );
myDictionary.Add( "1241308", "def" );
以下代码演示了 .Net 字典接受不同的键值,导致哈希冲突。没有抛出异常,并且字典键查找返回了预期的对象。
代码演示 .Net 字典可接受不同键发生哈希冲突,无异常抛出,键查找仍符合预期。
var hashes = new Dictionary<int, string>();
var collisions = new List<string>();
for (int i = 0; ; ++i)
{
string st = i.ToString();
int hash = st.GetHashCode();
if (hashes.TryGetValue( hash, out string collision ))
{
collisions.Add( collision );
collisions.Add( st );
break;
}
else
hashes.Add( hash, st );
}
Debug.Assert( collisions[0] != collisions[1], "Check we have produced two different strings" );
Debug.Assert( collisions[0].GetHashCode() == collisions[1].GetHashCode(), "Prove we have different strings producing the same hashcode" );
var newDictionary = new Dictionary<string, string>();
newDictionary.Add( collisions[0], "abc" );
newDictionary.Add( collisions[1], "def" );
Console.Write( "If we get here without an exception being thrown, it demonstrates a dictionary accepts multiple items with different keys that produce the same hash value." );
Debug.Assert( newDictionary[collisions[0]] == "abc" );
Debug.Assert( newDictionary[collisions[1]] == "def" );
Dictionary<TKey,TValue>
只被定义为在冲突的哈希码值面前能够正确地运行。任何关于它如何实现的信息都是实现细节,可能会在不同版本之间发生变化。 - JaredPar