2

我试图了解哈希表中的键排序/插入检查是如何工作的。我了解到,当我将对象添加到哈希表时,它会在运行时检查那里没有输入相同的键。

在我的测试中,我有 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();
    }        
}

}

4

3 回答 3

4

Dictionary将检查哈希码对象是否相等。散列仅用于提出“第一个近似值”以非常有效地找到可能相等的键。

您仅将委托覆盖Equals到使用引用相等的基本实现。这意味着任何两个不同的实例HashKey都是不相等的,即使它们具有相同的Key属性值。

你到底想达到什么目的?还是您只是想了解彼此之间的关系GetHashCode和关系?Equals

于 2010-11-15T09:21:29.057 回答
3

哈希码只是选择正确的存储桶来存储项目的启发式方法。仅仅因为 2 个项目共享相同的哈希码并不意味着它们是相等的。在发生冲突的情况下(与您的 1 个哈希码一样),我们将在存储桶中恢复为简单搜索以查找与搜索键相等的成员。由于您的相等性测试正在检查引用是否相同,因此没有两个项目会相等。

于 2010-11-15T09:23:22.817 回答
1

Equals比较 的参考HashKey

因为那是不同的实例,所以它们是不相等的。

Equals应该是这样的:

    public override bool Equals(object obj)
    {
        if (ReferenceEquals(this, obj))
            return true;

        var other = obj as Hashkey;

        return
            other != null &&
            Key.Equals(other.Key);
    }
于 2010-11-15T09:23:32.833 回答