1.8 阈值
resize()函数
threshold = newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
16*0.75 = 12
JDK1.7 put()
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
//初始化大小 根据要创建的数组大小计算出2次幂最接近的数字
inflateTable(threshold);
}
if (key == null)
//key为空的话直接放到数组[0]
return putForNullKey(value);
int hash = hash(key);//计算hash值 高位右移 使得高位参与hash运算 优化散列效果
int i = indexFor(hash, table.length);//根据hash值和数组长度算出脚标 h & (length-1);
//遍历数组[i]为头结点的链表
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
//找到key相同的元素的话 覆盖value 并且返回被覆盖的value
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
//没找到节点的话 添加新节点
addEntry(hash, key, value, i);
return null;
}
JDK1.7扩容 转移数据
/**
* Transfers all entries from current table to newTable.
*/
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
//遍历数组
for (Entry<K,V> e : table) {
//遍历链表
while(null != e) {
//保存next元素
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
//头插法 将新元素插入到新的table 并把新table原来的元素插入到后面
e.next = newTable[i];
//新元素作为数组的头结点
newTable[i] = e;
e = next;
}
}
}
JDK1.8 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; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
//创建数组
n = (tab = resize()).length;
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;//数组第一个元素如果hash和key一样的话直接覆盖value
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);
//深度达到8时候转化成红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
--------final void treeifyBin(Node<K,V>[] tab, int hash) {
--------int n, index; Node<K,V> e;
--------数组长度小于64的话会进行扩容而不是树化 而是进行扩容
--------if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
-------resize();
break;
}
//发现hash和key相同的话 退出循环
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
//指针指向下一个节点
p = e;
}
}
//找到了key相等的直节点 覆盖新值 返回旧值
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;
}