ハッシュテーブルでのキーの並べ替え/挿入チェックがどのように機能するかを理解しようとしています。オブジェクトをハッシュテーブルに追加すると、実行時に同じキーがまだ入力されていないかどうかがチェックされることを理解しました。
私のテストでは、キーが入力される2つのハッシュテーブルがあります。1-整数2-常に1を返すようにGetHashCodeメソッドをオーバーライドしたオブジェクト。
ここでの私の問題:同じintキーを追加すると最初のテストが壊れていますが、2番目のテストは壊れていません!どうして?挿入時にチェックする必要のあるハッシュコードはすべて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();
}
}
}