.Net HashSet唯一性计算完全基于哈希码吗?
我想知道 .Net HashSet
是否完全基于哈希码,或者是否也使用相等性?
我有一个特定的类,我可能会实例化数百万个实例,并且此时某些哈希码很可能会发生冲突。
我正在考虑使用 HashSet 来存储此类的一些实例,并且想知道它是否真的值得做 - 如果元素的唯一性仅由其哈希代码确定,那么这对我来说对于实际应用程序没有用处
MSDN 文档似乎是关于这个话题相当模糊 - 任何启发将不胜感激
I was wondering whether the .Net HashSet<T>
is based completely on hash codes or whether it uses equality as well?
I have a particular class that I may potentially instantiate millions of instances of and there is a reasonable chance that some hash codes will collide at that point.
I'm considering using HashSet's to store some instances of this class and am wondering if it's actually worth doing - if the uniqueness of an element is only determined on its hash code then that's of no use to me for real applications
MSDN documentation seems to be rather vague on this topic - any enlightenment would be appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,它也使用平等。根据定义,哈希码不需要是唯一的——任何假设它们是唯一的都会被破坏。
HashSet
是明智的。它使用IEqualityComparer
(默认为
EqualityComparer.Default
)来执行哈希代码生成和相等测试。No, it uses equality as well. By definition, hash codes don't need to be unique - anything which assumes they will be is broken.
HashSet<T>
is sensible. It uses anIEqualityComparer<T>
(defaulting toEqualityComparer<T>.Default
) to perform both hash code generation and equality tests.