/**
* @Author: 诉衷情の麻雀
* @Description: TODO
* @DateTime: 2023/7/9 10:01
**/
public class HashMapSource {
public static void main(String[] args) {
HashMap map = new HashMap<>();
map.put("java", 10);
map.put("php", 10);
map.put("java", 20);
System.out.println("map=" + map);
}
}
在创建HashMap的时候加上断点。
1.执行构造器new HasMap() 初始化加载因子loadfactor=0.75 HashMap$Node[] table = null
通过第一步debug我们看到,先初始化加载因子DEFAULT_LOAD_FACTOR
为0.75
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
同时HashMap的底层table数组为空
执行Put,调用hash方法,计算key的hash值(h = key.hashCode()) ^(h >>> 16))
- 因为加入的是int型数值,先进行装箱操作
key = "java" value = 10
接着执行hash(key)算法。通过Force step into,我们可以看到hash算法是这样的
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//通过传入的key的hashcode再进行按位异或无符号右移16位得到hash值
}
得到hash值之后,继续执行putVal
方法
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
先判断当前的table是否为空,如果当前为空,执行resize()
扩容方法
在resize()
方法里先初始化变量,先判断oldCap
是否大于0,显然不大于0,然后就走到了else{newCap = DEFAULT_INITIAL_CAPACITY
,默认初始分配16个大小空间,之后就是Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
创建table表,所以table表的类型其实是Node类型,此时的table如下
执行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;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null) //根据hash值得到在table表中的索引位置,判断这个索引位置是否为空,如果为空,就newNode(),直接把加入的k-v创建成一个Node,加入该位置即可。
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
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);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
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;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
之后就是newNode(hash, key, value,null)
创建新的节点,把java,10放入table中。
++modCount
修改次数+1。
if(++size > threshold) resize()
size是整个table表中有几个元素,当它到达临界值threshold = 加载因子 * 当前table容量 = 0.75 * 16 = 12
才会resize()----扩容。 很明显我们才增加了一个元素,没有到达临界值,所以当前不会扩容。
第一个put执行完毕
执行第二个put
此时的table
执行第三个put
因为在这里if ((p = tab[i = (n - 1) & hash]) == null)
算出来的hash值和第一次加的是一样的key都为Java,此时p不为null进入到else语句。三个else分支,有三种情况:
- 第一种情况:
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
这句代码的意思是table的索引位置的key的hash值相同且key是同一个对象, 或者equals比较之后是否相同 都不会再添加,把e指向p - 第二种情况
p instanceof TreeNode
是否为红黑树,按照红黑树的规则添加 - 第三种情况,是当table里有个值后面是个链表,它会遍历这条链表是否有相同的元素,如果没有,添加到链表的尾部。
else {
//如果找到的节点,后面是链表就循环比较
for (int binCount = 0; ; ++binCount) { //死循环
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);//如果整个链表,没有和它相同,就加到链表最后
//加入后,判断当前链表的个数,是否已经达到8个,到8个后,就调用treeifyBin方法进行红黑树的转换
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) //如果在循环比较的过程中,发现有相同,就break,替换value值
break;
p = e;
}
}
特别提醒:
//当调用treeifyBin后不会立即马上进行树化,而是在这个方法里面也有判断
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) //如果table为空,或者当前表的大小还小于MIN_TREEIFY_CAPACITY=64,再进行扩容,不会树化。
//否则才会真正树化(table表的大小>64且链表的长度到达8的时候)
//剪枝: 当数量减少慢慢由树再变成链表
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);
}
}
很明显我们这个第三个元素是要被替换,所以到了上面的if走完后没有机会添加来到了这段代码
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value; //替换变成了20
afterNodeAccess(e);
return oldValue;
}
之后table表还是两个元素,只不过Java对应的value被替换成20.
模拟HashMap树化
package com.sparrow.map_;
import java.util.HashMap;
import java.util.Objects;
/**
* @Author: 诉衷情の麻雀
* @Description: TODO
* @DateTime: 2023/7/9 17:49
**/
public class HashMapSource2 {
public static void main(String[] args) {
HashMap<Object, Object> map = new HashMap<>();
for (int i = 1; i <= 12; i++) {
map.put(new A(i), "hello");
}
System.out.println("hashMap=" + map);//12个key-value
}
}
class A {
private int num;
public A(int num) {
this.num = num;
}
//A对象的所有hashcode都一样,这样加入的元素都能落到table表中索引一样的位置
@Override
public int hashCode() {
return 100;
}
@Override
public String toString() {
return "\nA{" +
"num=" + num +
'}';
}
}
- 当i达到9时先进行table的扩容变成32
当再加2个元素,就满足两个条件table表的长度达到了64,链表的长度>8,就会进行树化,变成红黑树类型是HashMap$TreeNode