当前位置:网站首页>重写equals为什么要重写hashcode
重写equals为什么要重写hashcode
2022-07-17 00:33:00 【51CTO】
重写equals为什么要重写hashcode?
前提
先了解下object 类
实例
假设在业务上,我们认为名字相同的便是同一个人
猜想
如果不重写 hashcode 会发生什么
下面看看map的put操作发生了什么?
我们发现当有冲突时,判断的顺序如下
- 先比较key的hash值是否相等,再比较key的内存地址是否相等 或者 key的 equals 是否相等
- hash不相等,再比较是不是TreeNode类型
- 链表是否存在相等节点
由于我们认为名字相同的便是同一个人
当 put 的时候,先比较 student1 和 student2 的 hash 值,由于 student1 和 student2 是不同的对象,他们的 hashcode 方法是调用的 object.hashcode 方法,比较的是对象的地址,很明显,下面这个方法算出来的hash是不相等的
hash值不相等,也不是TreeNode类型,添加进链表
矛盾了
可是现在名字相同,但是在map中却存在两个人,很明显违背了我们的初衷
很明显,矛盾产生的原因就是调用了 object.hashcode 方法,计算出了不相等的hash值,如果hash值相等,便能满足下面的 if 语句
于是乎,我想设计使得名字相同的 student 产生相同的hash值
重写hashcode
我们知道不同的值可能会产生相同的hash值,但是在map中这个问题是不存在的,因为当hash值相等时,还会比较它的 equals方法,但是我们也应该尽量避免hash的碰撞,毕竟hash碰撞对性能还是有点影响的
综上,重写equals要重写hashcode就是为了避免像在map这样的数据结构中,禁止同一个key存在多个value值。
结束!!!
边栏推荐
猜你喜欢

工具及方法 - Excel插件XLTools

C language foundation day4 array

Rhce8 Study Guide Chapter 7 service management

乐视还有400多位员工?过着没有老板的神仙日子 官方出来回应了...

SQL之CASE WHEN用法详解

1. Introduction, analysis and implementation of asynctool framework

RHCE ansible second operation

RHCE Study Guide Chapter 5 VIM editor

JDBC连接Mysql数据库

The place where the dream begins ---- first knowing C language
随机推荐
rsync—远程同步
10. System safety and Application
ncnn Allocator内存分配器
工具及方法 - Excel插件XLTools
LETV has more than 400 employees? Living a fairy life without a boss, the official responded
ncnn 线程
OSPF comprehensive experiment
When the drain operation is performed on the work node, the number of pod copies is protected through the PDB
mysqldump: [Warning] Using a password on the command line interface can be insecure.
BiSeNetV2-面部分割 ncnn推理
Go language realizes sending SMS verification code and logging in
半年时间的思考
Learning network foundation
[redis] what is progressive rehash
3. Asynctool framework principle source code analysis
[MCU simulation] (VII) addressing mode - bit addressing
RHCE Study Guide Chapter 5 VIM editor
内置键盘连续444
Go语言 实现发送短信验证码 并登录
Que se passe - t - il lorsque vous compilez et installez une base de données MySQL bloquée dans un système Linux?