基于jdk8的HashMap源码解析
hashMap常见面试题总览
- 为什么重写Equals还要重写HashCode方法?
- HashMap如何避免内存泄漏问题?
- HashMap1.7底层是如何实现的?
- HashMapKey为null存放在什么位置?
- HashMap如何解决Hash冲突问题?
- HashMap底层采用单链表还是双链表?
- HashMap根据key查询的时间复杂度?
- HashMap如何实现数组扩容问题?
- HashMap底层是有序存放的吗?
- LinkedHashMap 和 TreeMap底层如何实现有序的?
- HashMap底层如何降低Hash冲突概率?
- HashMap中hash函数是怎么实现的?
- 为什么不直接将key作为哈希值而是与高16位做异或运算?
- HashMap如何存放1万条key效率最高?
- HashMap高低位与取模运算有那些好处?
- HashMap1.8如何避免多线程扩容死循环问题?
- 为什么加载因子是0.75而不是1?
- 为什么HashMap1.8需要引入红黑树?
- 为什么链表长度>8需要转红黑树?而不是6?
- 什么情况下,需要从红黑树转换成链表存放?
- HashMap底层如何降低Hash冲突概率?
- 如何在高并发的情况下使用HashMap?
- ConcurrentHashMap底层实现的原理?
为什么重写equals还要重写hashCode方法?
HashMap如何避免内存泄漏问题?
- 回答
- 为什么重写Equals还要重写HashCode方法?
- HashMap如何避免内存泄漏问题?
Hashcode方法:底层采用C语言编写,根据对象内存地址转换成整数类型
public native int hashCode();
基础1: 两个对象的hashCode值相等,对象不一定相等**
String a1="a";Integer a2=97;//97 97System.out.println(a1.hashCode());System.out.println(a2.hashCode());
引发hash碰撞问题,所以还要重写Equals,String类型的Equals方法已经帮我们重写,所以下面比较是不相等的
String a1="a";Integer a2=97;//falseSystem.out.println(a1.equals(a2));
String类型的Equals
/*** Compares this string to the specified object. The result is {@code* true} if and only if the argument is not {@code null} and is a {@code* String} object that represents the same sequence of characters as this* object.** @param anObject* The object to compare this {@code String} against** @return {@code true} if the given object represents a {@code String}* equivalent to this string, {@code false} otherwise** @see #compareTo(String)* @see #equalsIgnoreCase(String)*/public boolean equals(Object anObject) {if (this == anObject) {return true;}if (anObject instanceof String) {String anotherString = (String)anObject;int n = value.length;if (n == anotherString.value.length) {char v1[] = value;char v2[] = anotherString.value;int i = 0;while (n-- != 0) {if (v1[i] != v2[i])return false;i++;}return true;}}return false;}
Integer类型的Equals
/*** Compares this object to the specified object. The result is* {@code true} if and only if the argument is not* {@code null} and is an {@code Integer} object that* contains the same {@code int} value as this object.** @param obj the object to compare with.* @return {@code true} if the objects are the same;* {@code false} otherwise.*/public boolean equals(Object obj) {if (obj instanceof Integer) {return value == ((Integer)obj).intValue();}return false;}
基础2:两个对象equals相等,hashCode值不一定相等
UserEntity userEntity = new UserEntity("wei", 18);UserEntity userEntity1 = new UserEntity("wei", 18);//false 内存地址肯定不相等System.out.println(userEntity==userEntity1);//false Object默认实现了equals方法,本质还是==,比较内存地址System.out.println(userEntity.equals(userEntity1));
Object类的equals
public boolean equals(Object obj) {return (this == obj);}
结论:重写equals必须重写hashCode方法。
阿里规范
1.只要重写equals必须重写hashCode方法【强制】
2.Set、Map底层用hashCode和equals进行判断相等
3.String已重写equals和hashCode,所以可以用字符串作为Key【推荐】
不重写equals必须重写hashCode方法会导致内存无法回收(内存泄漏问题),同一个对象,一直创建新的空间存放。
HashMap1.7底层是如何实现的?
HashMapKey为null存放在什么位置?
基础:HashMap与HashTable之间的区别
HashMap底层如何实现
1.ArrayList集合实现,不需要考虑hash碰撞,时间复杂度为O(n):
2. JDK1.7基于数组和链表(h=(key.hashCode)^h>>>16),不发生冲突为O(1),发生冲突链表为O(n),hashCode相同,对象不同
3. JDK1.8基于数组和链表和红黑树
源码解读
1.默认参数
/*** The default initial capacity - MUST be a power of two.*///hashmap默认初始大小16,用位移做运算static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16/*** The maximum capacity, used if a higher value is implicitly specified* by either of the constructors with arguments.* MUST be a power of two <= 1<<30.*///2^30次方static final int MAXIMUM_CAPACITY = 1 << 30;/*** The load factor used when none specified in constructor.*///加载因子static final float DEFAULT_LOAD_FACTOR = 0.75f;/*** The bin count threshold for using a tree rather than list for a* bin. Bins are converted to trees when adding an element to a* bin with at least this many nodes. The value must be greater* than 2 and should be at least 8 to mesh with assumptions in* tree removal about conversion back to plain bins upon* shrinkage.*///链表大于8,转换成红黑树static final int TREEIFY_THRESHOLD = 8;/*** The bin count threshold for untreeifying a (split) bin during a* resize operation. Should be less than TREEIFY_THRESHOLD, and at* most 6 to mesh with shrinkage detection under removal.*///链表小于6,转换成红黑树static final int UNTREEIFY_THRESHOLD = 6;/*** The smallest table capacity for which bins may be treeified.* (Otherwise the table is resized if too many nodes in a bin.)* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts* between resizing and treeification thresholds.*///数组长度大于64,且链表长度大于8才会转换成红黑树static final int MIN_TREEIFY_CAPACITY = 64;
2.内部静态类
static class Node<K,V> implements Map.Entry<K,V> {final int hash;final K key;V value;Node<K,V> next;Node(int hash, K key, V value, Node<K,V> next) {this.hash = hash;this.key = key;this.value = value;this.next = next;}public final K getKey() { return key; }public final V getValue() { return value; }public final String toString() { return key + "=" + value; }public final int hashCode() {return Objects.hashCode(key) ^ Objects.hashCode(value);}public final V setValue(V newValue) {V oldValue = value;value = newValue;return oldValue;}public final boolean equals(Object o) {if (o == this)return true;if (o instanceof Map.Entry) {Map.Entry<?,?> e = (Map.Entry<?,?>)o;if (Objects.equals(key, e.getKey()) &&Objects.equals(value, e.getValue()))return true;}return false;}}
3.字段
/* ---------------- Fields -------------- *//*** The table, initialized on first use, and resized as* necessary. When allocated, length is always a power of two.* (We also tolerate length zero in some operations to allow* bootstrapping mechanics that are currently not needed.)*///数组 transient不能序列化transient Node<K,V>[] table;/*** Holds cached entrySet(). Note that AbstractMap fields are used* for keySet() and values().*/transient Set<Map.Entry<K,V>> entrySet;/*** The number of key-value mappings contained in this map.*/transient int size;/*** The number of times this HashMap has been structurally modified* Structural modifications are those that change the number of mappings in* the HashMap or otherwise modify its internal structure (e.g.,* rehash). This field is used to make iterators on Collection-views of* the HashMap fail-fast. (See ConcurrentModificationException).*/// fail-fast机制transient int modCount;/*** The next size value at which to resize (capacity * load factor).** @serial*/// (The javadoc description is true upon serialization.// Additionally, if the table array has not been allocated, this// field holds the initial array capacity, or zero signifying// DEFAULT_INITIAL_CAPACITY.)int threshold;/*** The load factor for the hash table.** @serial*///加载因子,如果不填写则采用默认加载因子final float loadFactor;
4.forEach修改报错
public final void forEach(Consumer<? super K> action) {Node<K,V>[] tab;if (action == null)throw new NullPointerException();if (size > 0 && (tab = table) != null) {int mc = modCount;for (int i = 0; i < tab.length; ++i) {for (Node<K,V> e = tab[i]; e != null; e = e.next)action.accept(e.key);}if (modCount != mc)throw new ConcurrentModificationException();}}}
5.put方法
public V put(K key, V value) {return putVal(hash(key), key, value, false, true);}
static final int hash(Object key) {int h;// null值放在0号位置,科学方法计算hash值,减少冲突return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);}
/*** Implements Map.put and related methods** @param hash hash for key* @param key the key* @param value the value to put* @param onlyIfAbsent if true, don't change existing value 当不存在时,则不更改现有值* @param evict if false, the table is in creation mode. 如果为false,则退出,表处于创建模式* @return previous value, or null if none*/final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {//数组+链表 n 数组长度 i链表存放位置Node<K,V>[] tab; Node<K,V> p; int n, i;//数组不存在或者数组长度为0,则调用扩容方法,懒加载if ((tab = table) == null || (n = tab.length) == 0)n = (tab = resize()).length;//hash不冲突,数组直接存放链表if ((p = tab[i = (n - 1) & hash]) == null)tab[i] = newNode(hash, key, value, null);else {Node<K,V> e; K k;//如果hash值相等且key值相等,将p赋值给e,等待做更新操作if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))e = p;//是红黑树else if (p instanceof TreeNode)e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);else {for (int binCount = 0; ; ++binCount) {// 遍历链表,到末尾添加元素if ((e = p.next) == null) {p.next = newNode(hash, key, value, null);//帮链表转换成红黑树,数组容量>=64 && 链表长度大于8if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1sttreeifyBin(tab, hash);break;}if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))break;p = e;}}// 存在则直接修改if (e != null) { // existing mapping for keyV oldValue = e.value;if (!onlyIfAbsent || oldValue == null)e.value = value;afterNodeAccess(e);return oldValue;}}++modCount;if (++size > threshold)resize();afterNodeInsertion(evict);return null;}
扩容方法
/*** Initializes or doubles table size. If null, allocates in* accord with initial capacity target held in field threshold.* Otherwise, because we are using power-of-two expansion, the* elements from each bin must either stay at same index, or move* with a power of two offset in the new table.** @return the table*/final Node<K,V>[] resize() {//旧的数组Node<K,V>[] oldTab = table;//获取旧数组的长度int oldCap = (oldTab == null) ? 0 : oldTab.length;// 旧数组的扩容阈值int oldThr = threshold;// 新的数组长度和新的扩容阈值int newCap, newThr = 0;// 如果旧的数组存在if (oldCap > 0) {if (oldCap >= MAXIMUM_CAPACITY) {threshold = Integer.MAX_VALUE;return oldTab;}else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&oldCap >= DEFAULT_INITIAL_CAPACITY)newThr = oldThr << 1; // double threshold 两倍扩容}// 旧数组存在,将旧的数组的长度赋值给新数组else if (oldThr > 0) // initial capacity was placed in thresholdnewCap = oldThr;//使用默认值进行初始化else { // zero initial threshold signifies using defaults//初始化数组容量=数组默认初始大小16newCap = DEFAULT_INITIAL_CAPACITY;// 初始化数组扩容阈值=链表加载因子*数组默认初始大小12newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);}//如果新数组扩容阈值为0if (newThr == 0) {//ft = 新的数组长度*加载因子,即计算阈值float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?(int)ft : Integer.MAX_VALUE);}//将新数组扩容阈值赋值到全局变量threshold = newThr;@SuppressWarnings({"rawtypes","unchecked"})Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];table = newTab;if (oldTab != null) {for (int j = 0; j < oldCap; ++j) {Node<K,V> e;if ((e = oldTab[j]) != null) {oldTab[j] = null;if (e.next == null)newTab[e.hash & (newCap - 1)] = e;else if (e instanceof TreeNode)((TreeNode<K,V>)e).split(this, newTab, j, oldCap);else { // preserve order//扩容是2的次方,分高位低位进行移动操作,插入新数组,尾插法Node<K,V> loHead = null, loTail = null;Node<K,V> hiHead = null, hiTail = null;Node<K,V> next;do {next = e.next;if ((e.hash & oldCap) == 0) {if (loTail == null)loHead = e;elseloTail.next = e;loTail = e;}else {if (hiTail == null)hiHead = e;elsehiTail.next = e;hiTail = e;}} while ((e = next) != null);if (loTail != null) {loTail.next = null;newTab[j] = loHead;}if (hiTail != null) {hiTail.next = null;newTab[j + oldCap] = hiHead;}}}}}return newTab;}
相关文章:

基于jdk8的HashMap源码解析
hashMap常见面试题总览 为什么重写Equals还要重写HashCode方法?HashMap如何避免内存泄漏问题?HashMap1.7底层是如何实现的?HashMapKey为null存放在什么位置?HashMap如何解决Hash冲突问题?HashMap底层采用单链表还是双…...

深度学习J1周-ResNet50算法实战与解析_鸟类识别(CNN)
🍨 本文为[🔗365天深度学习训练营]内部限免文章(版权归 *K同学啊* 所有) 🍖 作者:[K同学啊] 本周任务: ●1.请根据本文 TensorFlow 代码(训练营内部阅读),编写…...

SpringBoot中一行代码解决字符串向枚举类型转换的问题
1. 场景 在WEB开发,客户端和服务端传输的数据中经常包含一些这样的字段:字段的值只包括几个固定的字符串。 这样的字段意味着我们需要在数据传输对象(Data Transfer Object, DTO)中对该字段进行校验以避免客户端传输的非法数据持…...

Praat之基频分析
Praat之基频分析 测量基频F0的方法 自相关 Autocorrelation(易出现pitch-halving\pitch-double)窄带谱图 Narrowband spectrogram(第一谐波就是基频)倒谱分析 Cepstral analysis测量声门波 glottal pluse(通过波形&a…...

乡村企业门户网站
技术:Java、JSP等摘要:随着时代的发展,电脑与Internet已经进入我们的生活。信息时代的来临,知识经济的扩张,网站已越来越靠近我们的生活。据CNNIC报告显示,中国上网用户有6800万。通过Internet来经营运作一…...

Deploy Workshop|DIY部署环境,让OceanBase跑起来
2023 年 3 月 25 日,我们将在北京开启首次 OceanBase 开发者大会,与开发者共同探讨单机分布式、云原生、HTAP 等数据库前沿趋势,分享全新的产品 Roadmap,交流场景探索和最佳实践,此外,OceanBase 开源技术全…...
【CPP】定义一个类
一:当实现一个类的时候,编译器都做了什么 前言:当我们实现一个类的时候,编译器为我们做了什么;在对类进行操作的时候,有哪些特殊的成员函数可以帮助我们更好的操纵类; class A {A();//默认构造…...

谷歌广告投放步骤流程是什么?一文带你全方位了解实操细节
谷歌,大家都不陌生吧,一个人们很常用的搜索引擎。而谷歌还可以打广告,即谷歌广告,那这跟跨境电商有什么关心呢?东哥告诉大家,关系大了去了,毕竟如果用户搜索与我们相关的关键词,就有…...
TypeScript 怎么去查找类型定义的?
TypeScript 怎么去查找类型定义的?类型文件分类第三方库的类型自定义类型结论类型文件分类 我们项目中的类型文件分为两种:一类是第三方库的类型,一类是在项目中的自定义类型。 第三方库的类型 (1)Jquery࿱…...

NPM包管理器
文章目录一、NPM包管理器1、简介2、安装NPM3、使用npm管理项目3.1项目初始化3.2修改npm镜像3.3 npm install命令的使用3.4其它命令一、NPM包管理器 1、简介 什么是NPM NPM全称Node Package Manager,是Node.js包管理工具,是全球最大的模块生态系统&…...
IT英语记录
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录前言1、Classification2、Logistic Regression3、网络相关3.1 WAN(Wide Area Network)、LAN(Local Area Network)网络…...

SRS4.0 源码分析- RTC模块相关类
前言 本文介绍SRS4.0涉及RTC模块的C类,主要包括RTC Server和Session相关的。 SrsGoApiRtcPlay 处理webrtc client的播放请求,解析client的offer,并且生成server的answer,并且为这次请求创建一个session。SrsRtcServer 监听udp端…...

数位DP
数位dp的题目一般会问,某个区间内,满足某种性质的数的个数。 利用前缀和,比如求区间[l,r]中的个数,转化成求[0,r]的个数 [0,l-1]的个数。利用树的结构来考虑(按位分类讨论) 1081. 度的数量 #include<…...
剑指offer(一)-链表
(一)找出链表的环的入口结点 JZ23 链表中环的入口结点 中等 通过率:36.78% 时间限制:1秒 空间限制:64M 知识点链表哈希双指针 描述 给一个长度为n链表,若其中包含环,请找出该链表的环的入口结点…...

CDH大数据平台入门篇之搭建与部署
一、CDH介绍 1.CDH 是一个强大的商业版数据中心管理工具 提供了各种能够快速稳定运行的数据计算框架,如Spark; 使用Apache Impala做为对HDFS、HBase的高性能SQL查询引擎; 使用Hive数据仓库工具帮助用户分析数据; 提供CM安装HBas…...

Spark Join
Spark Join关联形式内关联外关联左外关联右外关联全外关联左半/逆关联关联机制NLJSMJHJ分发模式Join 选择等值 Join不等值 JoinJoin 按照关联形式(Join Types)划分 : 内关联、外关联、左关联、右关联 Join 按实现机制划分 : NLJ (Nested Loop Join) 、S…...
数字的转化规则?
数字的转化规则?js将字符串转换为数字的方式有哪些?1. 使用 parseInt()2. 使用 Number()3. 使用一元运算符 ()4.使用parseFloat()5. 使用 Math.floor()和Math.ceil()6.乘以数字7. 双波浪号 (~~) 运算符其它值到数字的转化规则1.Undefined 类型2.Null 类型…...

MySQL面试题-锁相关
目录 1.MySQL 锁的类型有哪些呢? 2.如何使用全局锁 3.如果要全库只读,为什么不使用set global readonlytrue的方式? 4.表级锁和行级锁有什么区别? 5.行级锁的使用有什么注意事项? 6.InnoDB 有哪几类行锁ÿ…...
Windows 终端编译 C代码
E:\My_SoftWare\Window gcc\windowbianji\mingw64\bin 此电脑--》属性--》系统--》高级系统设置--》环境变量--》Path--》新建--》粘贴路径 E:\My_SoftWare\Window gcc\windowbianji\mingw64\bin 打开命令终端 E: 回车 dir 显示所有文件 cd E:\My_SoftWare\Window gcc\C_co…...

SpringCloud:Feign的使用及配置
目录 Feign的使用及配置 1、Feign替代RestTemplate 2、使用Fegin步骤 3、自定义配置 4、Feign使用优化 5、Feign的最佳实践方式 Feign的使用及配置 1、Feign替代RestTemplate RestTemplate方式远程调用的问题 问题: 1、代码可读性差,编程体验不同…...
基于算法竞赛的c++编程(28)结构体的进阶应用
结构体的嵌套与复杂数据组织 在C中,结构体可以嵌套使用,形成更复杂的数据结构。例如,可以通过嵌套结构体描述多层级数据关系: struct Address {string city;string street;int zipCode; };struct Employee {string name;int id;…...
【杂谈】-递归进化:人工智能的自我改进与监管挑战
递归进化:人工智能的自我改进与监管挑战 文章目录 递归进化:人工智能的自我改进与监管挑战1、自我改进型人工智能的崛起2、人工智能如何挑战人类监管?3、确保人工智能受控的策略4、人类在人工智能发展中的角色5、平衡自主性与控制力6、总结与…...

LeetCode - 394. 字符串解码
题目 394. 字符串解码 - 力扣(LeetCode) 思路 使用两个栈:一个存储重复次数,一个存储字符串 遍历输入字符串: 数字处理:遇到数字时,累积计算重复次数左括号处理:保存当前状态&a…...

【Java_EE】Spring MVC
目录 Spring Web MVC 编辑注解 RestController RequestMapping RequestParam RequestParam RequestBody PathVariable RequestPart 参数传递 注意事项 编辑参数重命名 RequestParam 编辑编辑传递集合 RequestParam 传递JSON数据 编辑RequestBody …...

零基础设计模式——行为型模式 - 责任链模式
第四部分:行为型模式 - 责任链模式 (Chain of Responsibility Pattern) 欢迎来到行为型模式的学习!行为型模式关注对象之间的职责分配、算法封装和对象间的交互。我们将学习的第一个行为型模式是责任链模式。 核心思想:使多个对象都有机会处…...

学习STC51单片机32(芯片为STC89C52RCRC)OLED显示屏2
每日一言 今天的每一份坚持,都是在为未来积攒底气。 案例:OLED显示一个A 这边观察到一个点,怎么雪花了就是都是乱七八糟的占满了屏幕。。 解释 : 如果代码里信号切换太快(比如 SDA 刚变,SCL 立刻变&#…...

初探Service服务发现机制
1.Service简介 Service是将运行在一组Pod上的应用程序发布为网络服务的抽象方法。 主要功能:服务发现和负载均衡。 Service类型的包括ClusterIP类型、NodePort类型、LoadBalancer类型、ExternalName类型 2.Endpoints简介 Endpoints是一种Kubernetes资源…...
根目录0xa0属性对应的Ntfs!_SCB中的FileObject是什么时候被建立的----NTFS源代码分析--重要
根目录0xa0属性对应的Ntfs!_SCB中的FileObject是什么时候被建立的 第一部分: 0: kd> g Breakpoint 9 hit Ntfs!ReadIndexBuffer: f7173886 55 push ebp 0: kd> kc # 00 Ntfs!ReadIndexBuffer 01 Ntfs!FindFirstIndexEntry 02 Ntfs!NtfsUpda…...
「全栈技术解析」推客小程序系统开发:从架构设计到裂变增长的完整解决方案
在移动互联网营销竞争白热化的当下,推客小程序系统凭借其裂变传播、精准营销等特性,成为企业抢占市场的利器。本文将深度解析推客小程序系统开发的核心技术与实现路径,助力开发者打造具有市场竞争力的营销工具。 一、系统核心功能架构&…...

零知开源——STM32F103RBT6驱动 ICM20948 九轴传感器及 vofa + 上位机可视化教程
STM32F1 本教程使用零知标准板(STM32F103RBT6)通过I2C驱动ICM20948九轴传感器,实现姿态解算,并通过串口将数据实时发送至VOFA上位机进行3D可视化。代码基于开源库修改优化,适合嵌入式及物联网开发者。在基础驱动上新增…...