一、原理图:
二、结论:
(1) HashMap底层维护了Node类型的数组table,默认为null
(2)当创建对象时,将加载因子(lIoadfactor)初始化为0.75.
(3)当添加key-val时,通过key的哈希值得到在table的索引。然后判断该索引处是否有元素,如果没有元素直接添加。如果该索引处有元素,继续判断该元素的key和准备加入的key相是否等,如果相等,则直接替换val;如果不相等需要判断是树结构还是链表结构,做出相应处理。如果添加时发现容量不够,则需要扩容。
(4)第1次添加,则需要扩容table容量为16,临界值(threshold)为12 (16*0.75)
(5)以后再扩容,则需要扩容table容量为原来的2倍(32),临界值为原来的2倍,即24.依次类推
(6)在Java8中,如果一条链表的元素个数超过 TREEIFY_THRESHOLD(默认是8),并且3
table的大小 >= MIN TREEIFY CAPACITY(默认64),就会进行树化(红黑树)
三、源码:
1.执行构造器 : this.loadFactor = DEFAULT_LOAD_FACTOR; 加载因子:0.75
HashMap$Node[] table = null;
2.put方法: public V put(K key, V value) {Key="001" Value = "a"
return putVal(hash(key), key, value, false, true);
//hash(key) 得到key的哈希值
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
//2.1 hash(key)方法:通过传进去的key的hashCode值,按位异或无符号右移16位 返回
}
3.putVal()方法:
3.1resize()方法:Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i; //i辅助变量
if ((tab = table) == null || (n = tab.length) == 0)//判断table是否为空
n = (tab = resize()).length;//为空,扩容,resize方法
//取出hash值对应的table的索引位置的NOde,如果为空就加入
if ((p = tab[i = (n - 1) & hash]) == null)//得到索引位置,如果该索引位置为空,直接写进去
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;//辅助变量
//如果table索引位置的Node中key的hash值和新的key的hash值相同 或者 equals为真,进行覆盖
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)//如果table位置的Node是红黑树
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {//如果table位置的Node是一个链表
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;//Node+1,
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}