1. put()

 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
HashMap.Node<K,V>[] tab;//指向存储数组的引用
HashMap.Node<K,V> p;
int n, i;//n是数组长度,i是插入值的存储下标
//判断存储数组是否为空,即数组是否初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//计算出存储下标,并将数组中下标与插入值位置相同的赋给p
if ((p = tab[i = (n - 1) & hash]) == null)
//如果p为null则表示插入值的插入位置没有值,则直接插入
tab[i] = newNode(hash, key, value, null);
//p!=null
else {
HashMap.Node<K,V> e;
K k;
//判断p的key是否与插入值的key相等,如果相等,则不需要插入
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果p是红黑树节点
else if (p instanceof HashMap.TreeNode)
//直接将值插入到红黑树中,在红黑树的插入中同样会进行key是否存在的判断,如果有则返回那个节点,否则返回null
e = ((HashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//p是链表节点
else {
//遍历链表
for (int binCount = 0; ; ++binCount) {
//如果链表到头了,则将当前值插入到链表中
if ((e = p.next) == null) {
//插入
p.next = newNode(hash, key, value, null);
//判断链表的长度是否达到变成红黑树的长度
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//变成红黑树
treeifyBin(tab, hash);
//如果从这里break出去,e的值就为null
break;
}
//如果链表中存在key与插入值的key相同的节点,break
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//e!=null表示map中存在key与插入值的key相同,则更新值就行
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//对于HashMap来说是空函数,没有意义,LinkedHashMap中才有用
afterNodeAccess(e);
return oldValue;
}
}
//modCount是数组实际插入次数(根据代码来看,如果没有插入,只是更新的话是不会增加的)
++modCount;
//size是map中的元素个数(包括链表,红黑树以及数组上的元素),thresold是扩容阈值,如果达到这个值则扩容
if (++size > threshold)
resize();
//对于HashMap来说是空函数,没有意义,LinkedHashMap中才有用
afterNodeInsertion(evict);
return null;
}

2. 扩容

 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) { // table已初始化
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // 容量翻倍
}
else if (oldThr > 0) // table未初始化且已设置阈值,初始容量设为阈值
newCap = oldThr;
else { // table未初始化且未设置阈值
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) { // 1.table未初始化且已设置阈值 2.table已初始化但扩容后容量超过限制 3.table已初始化但原table容量小于默认值
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr; // 更新threshold
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab; // 更新table
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null; // 从原table中删除正在移动的元素
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 { // 链表节点
// 如果对于这里涉及到的低位、高位概念不懂,在我的另一篇博文ConcurrentHashMap源码解析(JDK8)中有介绍
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;
else
loTail.next = e;
loTail = e;
}
else { // 表示该节点是高位节点
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 将两条链表插入到新table中
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}

  虽然JDK8没有了扩容时死循环的问题,但是依然是线程不安全的,在多线程环境中请使用ConcurrentHashMap。

HashMap的put()与扩容的更多相关文章

  1. jdk7和8中关于HashMap和concurrentHashMap的扩容过程总结,以及HashMap死循环

    题外话:为什么要hashcode进行spread? 充分使用key.hashCode()的高16位信息,保证hash分布更分散, 扩容操作是新建2倍于原表大小的新表,并将原表结点拷贝一份放在新表中,对 ...

  2. 调试JDK源代码-一步一步看HashMap怎么Hash和扩容

    调试JDK源代码-一步一步看HashMap怎么Hash和扩容 调试JDK源代码-ConcurrentHashMap实现原理 调试JDK源代码-HashSet实现原理 调试JDK源代码-调试JDK源代码 ...

  3. HashMap 什么时候进行扩容呢

    HashMap扩容: 当HashMap中的元素越来越多的时候,碰撞的几率也就越来越高(因为数组的长度是固定的),所以为了提高查询的效率,就要对HashMap的数组进行扩容,数组扩容这个操作也会出现在A ...

  4. HashMap是如何进行扩容的?

    HashMap通过resize()方法进行扩容. 源码解析: resize()函数有两种使用情况: 一.当table数组为null时初始化hash表. 二.当table数组不为null时进行扩容. 1 ...

  5. HashMap什么时候进行扩容?

    Threshold:table数组元素个数size的大小超过threshold且且Node<K,V>[] table数组长度没有超过64时时table数组扩容.当hashmap中的元素个数 ...

  6. HashMap的扩容机制, ConcurrentHashMap和Hashtable主要区别

    源代码查看,有三个常量, static final int DEFAULT_INITIAL_CAPACITY = 16; static final int MAXIMUM_CAPACITY = 1 & ...

  7. 浅谈JAVA中HashMap、ArrayList、StringBuilder等的扩容机制

    JAVA中的部分需要扩容的内容总结如下:第一部分: HashMap<String, String> hmap=new HashMap<>(); HashSet<Strin ...

  8. JDK1.8 HashMap 扩容 对链表(长度小于默认的8)处理时重新定位的过程

    关于HashMap的扩容过程,请参考源码或百度. 我想记录的是1.8 HashMap扩容是对链表中节点的Hash计算分析. 对术语先明确一下: hash计算指的确定节点在table[index]中的链 ...

  9. 深入理解HashMap(原理,查找,扩容)

    面试的时候闻到了Hashmap的扩容机制,之前只看到了Hasmap的实现机制,补一下基础知识,讲的非常好 原文链接: http://www.iteye.com/topic/539465 Hashmap ...

随机推荐

  1. EMQ 与 mqtt 与 IOT设备

    1.IOT设备的特性 IOT(物联网things of internet)设备和传统的智能设备有什么区别,笔者总结下的IOT设备有如下特点: 硬件能力差(存储能力基本只有几MB,CPU频率低连使用HT ...

  2. cas 3.5.3服务器搭建+spring boot集成+shiro模拟登录(不修改现有shiro认证架构)

    因为现有系统外部接入需要,需要支持三方单点登录.由于系统本身已经是微服务架构,由多个业务独立的子系统组成,所以有自己的用户认证微服务(不是cas,我们基础设施已经够多了,现在能不增加就不增加).但是因 ...

  3. Java架构师之路(参考这个学习吧)

  4. git 版本找回方法

    在 git reset --hard 之后,git 的版本会回退. 这个时候,需要使用 git reflog 去查看之前的操作 然后, 找到相对应的 hash 数值. git reset --hard ...

  5. python限定方法参数类型、返回值类型、变量类型等

    typing模块的作用 自python3.5开始,PEP484为python引入了类型注解(type hints) 类型检查,防止运行时出现参数和返回值类型.变量类型不符合. 作为开发文档附加说明,方 ...

  6. Sql server 中将数据行转列列转行(二)

    老规矩,先弄一波测试数据,数据填充代码没有什么意义,先折叠起来: /* 第一步:创建临时表结构 */ CREATE TABLE #Student --创建临时表 ( StuName ), --学生名称 ...

  7. [LeetCode] 45. Jump Game II 跳跃游戏 II

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  8. [LeetCode] 169. Majority Element 多数元素

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  9. [LeetCode] 260. Single Number III 单独数 III

    Given an array of numbers nums, in which exactly two elements appear only once and all the other ele ...

  10. [LeetCode] 741. Cherry Pickup 捡樱桃

    In a N x N grid representing a field of cherries, each cell is one of three possible integers. 0 mea ...