碰撞是什么

问题描述 投票:0回答:2

我已经绞尽脑汁几个小时了,还是不明白什么是碰撞?

当两个不同的对象获得相同的哈希码时? 或者是当两个不同的对象进入字典数组中的同一个桶(位置)时?

还是别的东西?

static Dictionary<Number, string> dict = new Dictionary<Number, string>();

class Number
{
    private int X;

    public Number(int x)
    {
        X = x;
    }

    public override bool Equals(object obj)
    {
        Number other = obj as Number;
        return X.Equals(other.X);
    }

    public override int GetHashCode()
    {
        return X;
    }
}

public static void Main(string[] args)
{
    dict.Add(new Number(5), "Value5");
    dict.Add(new Number(2), "Value2");
    dict.Add(new Number(5), "Value52");
}

为什么链接在这里不起作用?

c# .net hash hashtable collision
2个回答
2
投票

还是不明白什么是碰撞?是当两个不同的对象获得相同的哈希码时吗?或者是当两个不同的对象进入字典数组中的同一个桶(位置)时?

当两个不同的对象获得相同的哈希码时。不过没关系。当

Equals
返回
true
时,哈希码必须相等。此外,当两个哈希码不同时,对象不能相等,所以
Equals
必须返回
false
。就这些了

但出于性能原因,它们应该分布均匀,因此避免太多(错误)碰撞。

在您的示例中,您得到一个

ArgumentException
,因为您添加了两个带有
X=5
的数字,这是
GetHashCode
Equals
中唯一检查的属性。


0
投票

Chaining 不起作用,因为

Add
方法返回 void。它应该被设计为返回字典本身的一个实例,以便链接工作。我也认为这会很有用。

© www.soinside.com 2019 - 2024. All rights reserved.