我试图了解哈希表中的键排序/插入检查是如何工作的。我了解到,当我将对象添加到哈希表时,它会在运行时检查那里没有输入相同的键。
在我的测试中,我有 2 个哈希表,其中填充了键: 1- 整数 2- 我重写了 GetHashCode 方法以始终返回 1 的对象。
我的问题是:虽然添加相同的 int 键时第一个测试会中断,但第二个测试不会!怎么来的?应该在插入时检查的哈希码都返回 1。
先感谢您!
我的代码:
class Collections
{
public Collections()
{
// Testing a hashtable with integer keys
Dictionary<int, string> d1 = new Dictionary<int, string>();
d1.Add(1, "one");
d1.Add(2, "two");
d1.Add(3, "three");
// d1.Add(3, "three"); // Cannot add the same key, i.e. same hashcode
foreach (int key in d1.Keys)
Console.WriteLine(key);
// Testing a hashtable with objects returning only 1 as hashcode for its keys
Dictionary<Hashkey, string> d2 = new Dictionary<Hashkey, string>();
d2.Add(new Hashkey(1), "one");
d2.Add(new Hashkey(2), "two");
d2.Add(new Hashkey(3), "three");
d2.Add(new Hashkey(3), "three");
for (int i = 0; i < d2.Count; i++)
Console.WriteLine(d2.Keys.ElementAt(i).ToString());
}
}
/// <summary>
/// Creating a class that is serving as a key of a hasf table, overring the GetHashcode() of System.Object
/// </summary>
class Hashkey
{
public int Key { get; set; }
public Hashkey(int key)
{
this.Key = key;
}
// Overriding the Hashcode to return always 1
public override int GetHashCode()
{
return 1;
// return base.GetHashCode();
}
// No override
public override bool Equals(object obj)
{
return base.Equals(obj);
}
// returning the name of the object
public override string ToString()
{
return this.Key.ToString();
}
}
}