HashMap的put方法源码分析
1.put方法八股文
首先给大家讲一下put()方法的八股文,大家可以先记,后面分析源码就会印象更深。
面试官:讲一下HashMap中的put()方法
答:HashMap中加入键值对的put()方法分为以下几步:
- 先调用key的hashCode()方法得到key的hash值,但是HashMap中存入的并不是key使用hashCode()方法直接得到的hash值,而是在put方法中有一个方法使hash=hash^(hash>>>16)的值
- 然后进行判断HashMap是不是刚初始化的(注意:JDK1.8是加入第一个元素之后才会初始化容量),如果是刚初始化的,那么需要初始化其容量,即数组容量为16,加载因子为0.75。
- 接下来通过hash和数组容量计算index,如果计算的这个index位置没有链表,那么这个新增的结点会直接加入到这个位置;如果这个index位置有结点,那么会使用equals、双等号以及key的hash是否相等来判断两个结点是否相同,如果一直遍历到最后一个结点仍未找到相同的结点,那么就将这个新结点放到这个链表的最后一个位置。
- 如果链表长度大于等于8,那么会对数组容量进行判断,如果数组容量大于64则会将链表转换为红黑树。
2.源码分析
//put()方法调用
public V put(K key, V value) {
//注意这块的hash(key)方法,传进去的不是key.hashCode()
return putVal(hash(key), key, value, false, true);
}
//解密hash(key)方法
static final int hash(Object key) {
int h;
//HashMap存入的key是可以为null的,当key为null的时候,存入index=0的位置
//真正的hash=key.hash^(key.hash>>>16)
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//接下来进入putVal()方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果HashMap刚刚创建,其数组容量和加载因子都未初始化,当加入第一个键值对时才会进行初始化
if ((tab = table) == null || (n = tab.length) == 0)
//这个resize()方法是扩容方法,下面会对这个方法进行分析
n = (tab = resize()).length;
//这块可以清除的看到index是怎么算的,即index=(n-1)&hash,n指的是数组容量
//如果index位置为空的话,那么就可以直接将元素插到这个位置上
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//如果index这个位置不为空,就说明有元素,会发生hash碰撞,形成链表
Node<K,V> e; K k;
//判断新增的结点和index上的结点是否是一样的,如果是一样的,那么新增的结点的value会覆盖掉原先结点的value
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果新增结点是TreeNode类型的,意思就是当数组容量>64且链表长度>8,链表成为了红黑树,那么直接向树中插入元素
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//最后剩下的一种结果就是遍历这个链表,如果链表中有结点相同,那么会覆盖
//如果链表的长度>8,那么会进行数组容量判断,看数组容量是否>8
for (int binCount = 0; ; ++binCount) {
//遍历链表,找到最后一个结点,将新结点链接到最后一个结点后面
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果链表长度>8,那么会进入treeifyBin()方法进行判断数组容量
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//进去之后判断数组容量,如果大于64,那么会转换成红黑树
//下面会对这个方法进行分析
treeifyBin(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 key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//执行到这块,说明新增结点成功加到链表中,且无覆盖
++modCount;
//判断此时数组元素个数和threshole大小,若前者大,则需要扩容
//threshold:此时数组最大容量*负载因子
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//解密resize()方法
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
//判断HashMap是否为第一次添加元素,如果是,则进行初始化
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//旧HashMap数组的阈值
int oldThr = threshold;
//新容量,新阈值
int newCap, newThr = 0;
if (oldCap > 0) {
//当旧容量大于最大HashMap数组容量时,即64
if (oldCap >= MAXIMUM_CAPACITY) {
//让阈值等于int类型的最大值
threshold = Integer.MAX_VALUE;
//这个是一个伏笔,后面会对oldTab进行判断
//也是链表长度>8且数组长度>64之后,链表->红黑树
return oldTab;
}
//如果扩容之后的新容量小于HashMap最大容量,并且旧容量大于初始化容量
//这块也可以看到HashMap的扩容原理,即newCap=oldCap << 1
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 threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
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;
//如果oldTab不为null,也就是上面进行判断HashMap的数组容量大于64的时候,会返回一个oldTab
//这块来进行链表->红黑树的操作
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
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);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
//解密treeifyBin()方法
//这个方法是上面对链表进行遍历时,如果链表长度>8,就会进入这个方法
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//仍然是oldTab,上面resize()方法中对是否需要转换为红黑树的一个标志
//即oldTab不为null,那么需要进行链表->红黑树
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
//oldTab为null则扩容就行
resize();
//链表->红黑树
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);
}
}
能够读到这块的都是非常用耐心的,如果以上源码分析有什么错误,欢迎大家在评论区一起交流!