GetHashCode中的空集合与空集合 [英] Null vs Empty Collections in GetHashCode

查看:88
本文介绍了GetHashCode中的空集合与空集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的 GetHashCode 的实现中,当 Collection null 或为空都将导致 0 的哈希码。

In the implementation of GetHashCode below, when Collection is null or empty will both result in a hash code of 0.

一位同事建议返回一个随机的硬编码数字,例如 19 以区别于 null 集合。我为什么要这样做?我为什么要关心 null 或空集合会产生不同的哈希码?

A colleague suggested return a random hard coded number like 19 to differentiate from a null collection. Why would I want to do this? Why would I care that a null or empty collection produces a different hash code?

public class Foo
{
    public List<int> Collection { get; set; }
    // Other properties omitted.

    public int override GetHashCode()
    {
        var hashCode = 0;
        if (this.Collection != null)
        {
            foreach (var item in this.Collection)
            {
                var itemHashCode = item == null ? 0 : item.GetHashCode();
                hashCode = ((hashCode << 5) + hashCode) ^ itemHashCode;
            }
        }

        return hashCode;
    }
}


推荐答案

GetHashCode 的设计应尽可能地减少发生冲突的次数。虽然不可避免发生 some 哈希冲突,但您需要注意哪些类型的对象发生冲突,哪些类型的数据将存储在基于哈希的集合中,并努力确保存储在同一个集合中的对象类型发生碰撞的可能性较小。

The design of GetHashCode is that it is supposed to minimize the number of collisions that will take place, as best as it can. While having some hash collisions is inevitable, you'll want to be mindful of what types of objects are colliding, what type of data are going to be stored in your hash based collections, and working to ensure that types of objects stored together in the same collection are less likely to collide.

因此,如果您碰巧知道这种类型的基于散列的集合将如何使用它们,并且其中可能同时存在空对象和空对象,则可以提高性能,防止它们碰撞。如果您怀疑在同一个集合中同时存在null和null值的可能性不大,那么实际上就不必担心它们发生冲突了。

So if you happen to know something about how hash-based collections of this type are going to be used, and that there are likely to be both null and empty objects in them, then it would improve the performance to have them not collide. If you suspect that having both a null and empty value in the same collection is not particularly likely, then having them collide isn't actually a concern.

这篇关于GetHashCode中的空集合与空集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆