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

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

问题描述

在下面的GetHashCode的实现中,当Collectionnull或为空时,都会产生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 的设计是它应该尽可能减少将发生的冲突数量.虽然一些哈希冲突是不可避免的,但您需要注意哪些类型的对象发生冲突,哪些类型的数据将存储在基于哈希的集合中,并努力确保存储在同一集合中的对象类型不太可能发生冲突.

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 和空值的可能性不大,那么让它们发生冲突实际上并不是一个问题.

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天全站免登陆