数组+链表(超过阈值变红黑树);
If the map previously contained a mapping for the key, the old value is replaced.
通过key,计算hash值得出数组下标,即要放的位置,当多个hash值相同,即在此下标位置创建一个链表,存放node,当在大数据情况下,链表很可能达到并超过阈值,此时链表变红黑树(时间复杂度由:n--》logn);
扩容因子:java中扩容因子0.75,越接近此,说明hash碰撞发生概率越大,导致链表长度增加,最终导致性能变慢,所当数据达到一定程度时候需要扩容,但扩容很消耗时间与空间性能,如通过key的hash计算的位置也相对变化。
如下的put方法中:tab[i] = newNode(hash, key, value, null);在这个Node[]数组中,插入
//1、hash是将key做了一遍hash运算,将hash值,随同key value一起传入
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, I;
//2、如果Node节点数组为null ,或者长度为0,进行数组的初始化resize()
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//如果节点p,也就是n-1 与hash 与运算后得到的 数组下标i的位置,为null,将新
//node插入数组下标i的位置
if ((p = tab[i = (n - 1) & hash]) == null)
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
//下面方法中会有数组长度<64初始化;>64才建treenode
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;
}
网友评论