当前位置:网站首页>为什么hash%length==hash&(length-1)的前提是 length 是 2 的 n 次方
为什么hash%length==hash&(length-1)的前提是 length 是 2 的 n 次方
2022-04-23 12:02:00 【滕青山YYDS】
Hash值的范围在-2147483648 到 2147483647,前后加起来大概 40 亿的映射空间,但是我们不可能去创建一个40亿大小的数组,HashMap的默认数组大小是16。
所以在拿到Hash值之后需要对数组长度进行取余,得到的余数就是在数组的索引位置。
那么为什么说hash%length == hash&(length-1)
的前提是 length 是 2 的 n 次方?
从二进制的角度来看,对一个数右移1位就是除以2,它剩余的二进制数字所表示的就是除以2得到的结果,那么被移出的数字就是余数。
也就是说,对一个数右移n位,就是让这个数除以2的n次方,被移出的n位数字就是我们想要的余数。
当数组的长度是2的n次方的时候,我们让hash对它取余就是想要hash的最右边的n位数。
此时,数组的长度在二进制的数字表示就是1后面跟着n个0,如果对它-1,也就是length-1,此时二进制的数字表示就是前面都是0,后面跟着n个1。
那么我们就让hash跟length-1进行位与运算,也就得到了hash的后n位也就是想要的余数。
之所以采用hash&(length-1)
来取余,而不是直接进行hash%length
的原因在于:位运算计算速度更快,更加高效。
参考:
Java集合常见知识点&面试题总结(下) | JavaGuide
二进制按位与&及求余数 | Perkins4j2的技术博客
版权声明
本文为[滕青山YYDS]所创,转载请带上原文链接,感谢
https://tengqingshan.blog.csdn.net/article/details/124360052
边栏推荐
- Here comes the detailed picture and text installation tutorial of H5 game
- 配电房远程综合监控系统在10kV预制舱项目中的应用
- TclError: no display name and no $DISPLAY environment variable
- 第四章 为物化视图启用和禁用IM列存储(IM 4.6)
- Im architecture: CPU architecture: SIMD vector processing (im-2.3)
- Maker education for primary and middle school students to learn in happiness
- VMware virtual machines export hard disk vmdk files using esxi
- 1.Electron开发环境搭建
- 力扣-1137.第N个泰波那契数
- IDEA 中 .properties文件的中文显示乱码问题的解决办法
猜你喜欢
Tips for installing MySQL service in windows11: Install / Remove of the Service denied
Exploring the equipment and teaching of robot education
Overall plan management mode in maker Education
Maker education for primary and middle school students to learn in happiness
运行报错:找不到或无法加载主类 com.xxx.Application
Yunna | how to manage the company's fixed assets and how to manage fixed assets
软件测试基础DAY2-用例执行
Share two practical shell scripts
云呐|固定资产盘点中,支持多种盘点方式(资产清查盘点)
Win10 splash screen after startup
随机推荐
How imeu is associated with imcu (IM 5.5)
Yunna | how to manage the company's fixed assets and how to manage fixed assets
激活函数之sigmoid函数
第五章 使用In-Memory表达式优化查询(IM 5.1)
Optimize connections using connection groups (IM 6)
How to expand the capacity of the server in the 100 million level traffic architecture? Well written!
oh-my-lotto
第四章 为IM 启用填充对象之启用和禁用列(IM-4.3 第三部分)
云呐|如何管理好公司的固定资产,固定资产管理怎么做
How the database fills in IM expressions (IM 5.4)
Next. JS static data generation and server-side rendering
用户接口和IM表达式(IM 5.6)
Windows2008系统如何切换PHP版本
A detailed explanation of head pose estimation [collection of good articles]
IDEA 中 .properties文件的中文显示乱码问题的解决办法
SOFA Weekly | 年度优秀 Committer 、本周 Contributor、本周 QA
抓包整理————tcp 协议[八]
IDEA设置版权信息
Database design of simple voting system
What is a gateway