为什么我们检查哈希如果我们要检查等于什么? [英] Why do we check hash if we are going to check equals anyways?

查看:228
本文介绍了为什么我们检查哈希如果我们要检查等于什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果两个对象相等,那么 hashcode 必须相同。那么为什么在 HashMap 中的任何检查都做 -

  if(e .hash == hash&&((k = e.key)== key ||(key!= null&& key.equals(k)))){


$ 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 hashes.

Since hash is of type int, comparing 2 ints 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屋!

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