为什么hashCode()和equals()都存在 [英] Why both hashCode() and equals() exist

查看:136
本文介绍了为什么hashCode()和equals()都存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么java Object类有两个方法hashcode()和equals()?其中一个看起来多余,它渗透到最底层的派生类?

解决方案

为什么你认为一个是多余的?他们说不同的东西:




  • hashCode 是给我一些有效的看法两个对象可能是否相等

  • 等于是检查此对象是否真的等于另一个



你绝对需要两者 - 虽然我不认为他们真的应该首先在Object中。 / p>

为了使用哈希表执行高效的查找,你绝对需要哈希码 - 你绝对需要进一步的相等检查,因为哈希碰撞(有例如,比哈希码更可能的字符串。


why java Object class has two methods hashcode() and equals()? One of them looks redundant and its percolated to the bottom most derived class?

解决方案

Why do you think one is redundant? They say different things:

  • hashCode is "give me some way of efficiently seeing whether two objects are likely to be equal"
  • equals is "check whether this object is genuinely equal to another"

You definitely need both - although I don't believe they should really be in Object in the first place.

You absolutely need hash codes in order to perform efficient lookups with hash tables - and you absolutely need further equality checks because hashes will collide (there are far more possible strings than hash codes, for example).

这篇关于为什么hashCode()和equals()都存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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