在哪种情况下,您通常会覆盖“获取哈希码"方法?确切地重写此方法对我们有何帮助? [英] In which condition do you typically override Get Hash Code method? How exactly overriding this method helps us?

查看:70
本文介绍了在哪种情况下,您通常会覆盖“获取哈希码"方法?确切地重写此方法对我们有何帮助?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们通常在哪种情况下覆盖获取哈希码"方法?

In which condition do we typically override Get Hash Code method?
How exactly overriding this method helps us?

推荐答案

某些类型的集合使用对象的哈希码来加快搜索和其他操作.为了使这些集合正常工作,必须将所有应视为相同的对象都必须返回相同的哈希码.不应被视为相同的对象应该不太可能返回相同的哈希码.如果集合中的两个对象不同,但返回的对象具有代码,则这种情况称为哈希冲突.偶尔发生哈希冲突通常是不可避免的,但过于频繁的哈希冲突会降低性能.

通常,在与重写Object.Equals基本上相同的情况下,应该重写Object.GetHashCode.如果Object.Equals被覆盖,以便它可以与两个不同的对象返回等于"(例如字符串),则Object.GetHashCode必须被覆盖,以便它将为所有对象返回相同的值.彼此相等.
Some types of collection use the hash code of objects to expedite searches and other operations. For these collections to work correctly, it is necessary that any objects which should be regarded as identical must return the same hash code. Objects which should not be regarded as identical should be unlikely to return the same hash code. If two objects in a collection are different, but return the same has code, such an occurrence is called a hash collision. Occasional hash collisions are often inevitable, but overly-frequent hash collisions will degrade performance.

Generally, one should override Object.GetHashCode under essentially the same circumstances as one would override Object.Equals; if Object.Equals is overridden so that it could return ''equals'' with two distinct objects (as could happen with e.g. strings) then Object.GetHashCode must be overridden so that it will return the same value for any and all objects that are equal to each other.


这篇关于在哪种情况下,您通常会覆盖“获取哈希码"方法?确切地重写此方法对我们有何帮助?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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