当前位置:网站首页>为什么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
边栏推荐
- Blog post navigation (real-time update)
- 欣旺达宣布电池产品涨价 此前获“蔚小理”投资超10亿
- IDEA 代码质量规范插件SonarLint
- IDEA 中 .properties文件的中文显示乱码问题的解决办法
- Database design of forum system
- Fabric 1.0 source code analysis (33) implementation of peer channel command and subcommand
- Laravel adds custom helper functions
- ThinkPHP adds image text watermark to generate promotion poster with QR code
- 智能多线弹性云增加独立的IP地址,如何实现多线功能?
- AcWing 1874. Moo encryption (enumeration, hash)
猜你喜欢

Nacos Foundation (9): Nacos configuration management from single architecture to microservices

Here comes the detailed picture and text installation tutorial of H5 game

Running error: unable to find or load the main class com xxx. Application

论文解读(CGC)《CGC: Contrastive Graph Clustering for Community Detection and Tracking》

Idea code quality specification plug-in sonarlint
![抓包整理————tcp 协议[八]](/img/ae/4957a997af725a1bf3f61cb24fc717.png)
抓包整理————tcp 协议[八]

On the integration of steam education in early childhood education

5个免费音频素材网站,建议收藏

Tensorflow uses keras to create neural networks

Nacos Foundation (6): Nacos configuration management model
随机推荐
Nacos Foundation (8): login management
The fourth chapter is about enabling and disabling the im column storage of table space for im enabled filling objects (IM 4.5)
Precautions for PCB
Nacos Foundation (6): Nacos configuration management model
Next. JS static data generation and server-side rendering
IDEA 中 .properties文件的中文显示乱码问题的解决办法
VMware virtual machines export hard disk vmdk files using esxi
如果你是一个Golang面试官,你会问哪些问题?
配电房远程综合监控系统在10kV预制舱项目中的应用
How to count fixed assets and how to generate an asset count report with one click
The fourth chapter is to enable the filling object of IM and enable ADO for im column storage (IM 4.8)
Share two practical shell scripts
Idea code quality specification plug-in sonarlint
C# F23. Stringsimilarity Library: String repeatability, text similarity, anti plagiarism
Blog post navigation (real-time update)
什么是网关
On lambda powertools typescript
第二十三课 临时对象
IMEU如何与IMCU相关联(IM 5.5)
Sigmoid function of activation function