为什么我们检查哈希如果我们要检查等于什么? [英] Why do we check hash if we are going to check equals anyways?
问题描述
如果两个对象相等,那么 hashcode 必须相同。那么为什么在 HashMap
中的任何检查都做 -
if(e .hash == hash&&((k = e.key)== key ||(key!= null&& key.equals(k)))){
$ c $
$ p $ if(( k = e.key)== key ||(key!= null&& key.equals(k)))){
如果两个对象相等,则hashcode必须相同。
在这种情况下,采取另一种方式:如果两个对象的哈希码不同,它们不能相等
所以,在这里我们只是简单地比较 equals()
,首先比较 hash
es。由于 hash
类型为 int
,所以比较2 int
s不是一个昂贵的操作(只使用一个机器指令 - if_icmp< cond>
。
equals()
方法可能涉及复杂的操作,当然这使得它成为一种昂贵的操作,相比之下 int
比较。因此,我们只对哈希
比较以前的退出。 If two objects are equal then hashcode must be same. Then why does the any check in HashMap
do -
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
Instead of simply
if ((k = e.key) == key || (key != null && key.equals(k)))) {
If two objects are equal then hashcode must be same.
In this case, take it the other way: "If hashcodes of two objects are different, they can't be equal"
So, here we are simply short-circuiting the comparison using equals()
by first comparing the hash
es.
Since hash
is of type int
, comparing 2 int
s is not an expensive operation (Just uses a single machine instruction - if_icmp<cond>
.
On the other hand, equals()
method for various objects might involve complex operations, of course making it an expensive operation in compared to int
comparison. So, we just do hash
comparison for earlier exit.
这篇关于为什么我们检查哈希如果我们要检查等于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!