说明
本文主要是对jdk1.8的HashMap的put方法的源码进行了分析,主要介绍点包括:put操作流程、map初始化、map扩容、链表转红黑树等源码,如若在分析当中有错误,请各位支出,以便更新,谢谢;
1.map.put()源码注释
/**
* 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.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//定义数组节点变量
Node<K,V>[] tab;
//定义链表或红黑色节点变量
Node<K,V> p;
//定义数组长度变量n、局部变量i
int n, i;
//判断当前table是否为空
if ((tab = table) == null || (n = tab.length) == 0)
//初始化tab大小,默认初始化大小为16(2的指数幂),负载因子为0.75(时间和空间权衡的结论)
n = (tab = resize()).length;
//判断数组某一节点是否为null
/**
* 此处讲解(n - 1) & hash
*1.n为数据的大小(2的指数幂),以2^4即16为例,那么(n-1)的二进制表示为0000 1111
* 2.hash是将key进行了hash运算,得到一个int类型的数
* 3.将此数和(n-1)进行与运算(无论怎样,数据大小取决于hash值的后四位),将得到0~(n-1)中的值 *(实际为0~(n-1)轮循的值)赋予临时变量i
* 4.从数组中拿到第i个值,付给链表p,并判断是否为空
*/
if ((p = tab[i = (n - 1) & hash]) == null)
//数组第i为null则插入节点数据
tab[i] = newNode(hash, key, value, null);
//数组第i不为null则操作链表
else {
//定义局部链表节点变量e和定义类型局部变量k
Node<K,V> e; K k;
//判断链表p当前节点的hash值是否与key的hash相等
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//如果相等则赋予临时变量e
e = p;
//判断p节点是否为红黑树节点
else if (p instanceof TreeNode)
//如果未红黑树节点,则添加到红黑树对应节点中
/**为红黑树节点的概率非常小,jdk1.8默认当链表长度为8时,转换为红黑树,
*jdk1.8采用了《泊松分布》统计理论,所以每个链表长度达到8的概率非常小
**/
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//不满足以上两种条件,则在俩表中插入节点
else {
for (int binCount = 0; ; ++binCount) {
//判断p的下一节点是否为null,并赋给变量e
if ((e = p.next) == null) {
//p的下一节点为空,则插入
p.next = newNode(hash, key, value, null);
//判断链表p的长度是否大于等于默认转换为红黑树的值
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//进行链表转红黑树的操作
treeifyBin(tab, hash);
//节点插入完成,跳出循环
break;
}
//如果p的下一节点不为null,判断key的hash是否与他的hash相等
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
//如果相等,则跳出循环
break;
//p指向下一个节点
p = e;
}
}
//如果e不为空,则表明要插入的key已经存在于map中
if (e != null) { // existing mapping for key
//获得key对应的旧值
V oldValue = e.value;
//判断旧值是否为空,并且是否覆盖(jdk1.8默认覆盖旧值)
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//jdk提供的对e节点操作的扩展方法
afterNodeAccess(e);
//返回旧值
return oldValue;
}
}
++modCount;
//判断数组大小是否大于扩容阈值
if (++size > threshold)
//扩容
resize();
//扩展构造方法
afterNodeInsertion(evict);
return null;
}
2.HashMap初始化容量或扩容
/**
* 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) {
//旧数组容量大于最大值,则扩容阈值赋值为Integer的最大值,之后再无法横向扩容
threshold = Integer.MAX_VALUE;
return oldTab;
}
/**
*(newCap = oldCap << 1) < MAXIMUM_CAPACITY将旧数组容量大小扩大两倍(oldCap << 1二进制左移
*一位),判断是否小于最大容量
*oldCap >= DEFAULT_INITIAL_CAPACITY判断是否大于初始化容量大小
**/
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//将扩容阈值扩大2倍
newThr = oldThr << 1; // double threshold
}
//判断旧的扩容阈值是否大于零
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//oldCap的大小为0表明初始化
else { // zero initial threshold signifies using defaults
//初始化数组大小为默认值16
newCap = DEFAULT_INITIAL_CAPACITY;
//初始化扩容阈值为默认大小16*扩容因子0.75
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
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;
//判断数据的第i个节点数据是否为空,并赋值给e
if ((e = oldTab[j]) != null) {
//将旧数组的第i值赋值给e后,将当前节点置为null;
oldTab[j] = null;
//判断当前数组元素是否有下一个节点
if (e.next == null)
//根据新的容量大小进行hash与运算确定位置,并将e赋给新数组
newTab[e.hash & (newCap - 1)] = e;
//如果e为红黑树的节点
else if (e instanceof TreeNode)
//将红黑树节点分割重组
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//以下进行链表的迁移
else { // preserve order
//此处定义链表节点迁移时的高低位节点局部变量,jdk1.8引入高低位节点的目的是解决1.8之
//前版本存在的产生环形链表,导致死循环
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
//得到当前节点的下一节点
next = e.next;
//hash的值与旧的容量进行与运算,得到的结果只有0、1两个值,用0便是低位
if ((e.hash & oldCap) == 0) {
//判断低位尾是否为null,将e节点赋给低位头
if (loTail == null)
loHead = e;
//否则将e节点赋值给低位尾部的下一节点
else
loTail.next = e;
//低位尾部指向它的下一节点e
loTail = e;
}
else {
//判断高位尾是否为null,将e节点赋给高位头
if (hiTail == null)
hiHead = e;
//否则将e节点赋值给高位尾部的下一节点
else
hiTail.next = e;
//高位尾部指向它的下一节点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;
}
3.链表转红黑树操作
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//数组为空或数组长度小于默认转红黑树的阈值,则进行扩容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
//从tab中拿出不为空的节点
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
//进行转换
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}