jdk1.8put原理
- 如果定位到数组的元素为空,则进行直接插入
- 若数组的元素不为空,key值相同则进行覆盖,若Key值不相同,判断是否为树节点,不是则遍历插入,当插入后的长度大于8时,转换为红黑树,若是树节点,则红黑树插入
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// table未初始化或者长度为0,进行扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// (n - 1) & hash 确定元素存放在哪个桶中,桶为空,新生成结点放入桶中(此时,这个结点是放在数组中)
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 桶中已经存在元素
else {
Node<K,V> e; K k;
// 比较桶中第一个元素(数组中的结点)的hash值相等,key相等
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 将第一个元素赋值给e,用e来记录
e = p;
// hash值不相等,即key不相等;为红黑树结点
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;
}
// 判断链表中结点的key值与插入的元素的key值是否相等
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
// 相等,跳出循环
break;
// 用于遍历桶中的链表,与前面的e = p.next组合,可以遍历链表
p = e;
}
}
// 表示在桶中找到key值、hash值与插入元素相等的结点
if (e != null) {
// 记录e的value
V oldValue = e.value;
// onlyIfAbsent为false或者旧值为null
if (!onlyIfAbsent || oldValue == null)
//用新值替换旧值
e.value = value;
// 访问后回调
afterNodeAccess(e);
// 返回旧值
return oldValue;
}
}
// 结构性修改
++modCount;
// 实际大小大于阈值则扩容
if (++size > threshold)
resize();
// 插入后回调
afterNodeInsertion(evict);
return null;
}
设计的优点
- 将链表转换为红黑树,减少搜索时间
- 数组存放位置是通过(n-1)&hash去计算,而Hash算法通过扰动减少元素插入时的碰撞,使元素分布更加均匀。
static final int hash(Object key) {
int h;
// key.hashCode():返回散列值也就是hashcode
// ^ :按位异或
// >>>:无符号右移,忽略符号位,空位都以0补齐
// hash值的16位前和后16位亦或,增加扰动
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
- resize方法中的扩容时,移动到哪个桶中的方法效率很高,计算桶位置是通过(容量大小-1)^hash值,扩容是扩大两倍,向左位移了一位,而原有的hash值不变,和新的容量大小-1与计算后,只有最前面的一个值可能是1或者是0,若是0则位置不变,若是1则是原有位置大小加上原有的容量大小,故将原有元素进行位置移动,通过e.hash&oldCap不等于0则移动到j + oldCap该位置,若等于0则位置不动
final Node<K,V>[] resize() {
// 原数组
Node<K,V>[] oldTab = table;
// 原容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 原threshold值(容量*负载因子)
int oldThr = threshold;
int newCap, newThr = 0;
// 如果原容量大于 0
if (oldCap > 0) {
// 如果数组长度达到最大上限,更新 threshold,不进行扩容
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 否则容量*2 threshold*2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// 如果在构造函数中设置了初始 threshold 使用 HashMap(int initialCapacity, float loadFactor)创建 Map
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
// 如果原容量且原threshold 都为0,进行初始化操作
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 如果 newThr == 0 ( oldThr > 0 为 true 时该判断才会为 true)
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
// 计算新的 threshold
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
// 更新 threshold
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
// 根据newCap 构造一个新数组
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
// 更显table引用
table = newTab;
// 如果 oldTab 不为 null,表明为扩容操作,否则为table初始化操作
if (oldTab != null) {
// 遍历原数组中的元素
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
// 如果该元素不为 null
if ((e = oldTab[j]) != null) {
// 将原数组该索引设置为null,方便回收
oldTab[j] = null;
// 如果该节点下一个元素为null,表明该节点只存在一个元素
if (e.next == null)
// 将该节点设置到新数组中去
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 如果节点为 TreeNode 类型,按照对应方式设置到新数组中
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
// 如果是数量大于1的链表
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
// 此处操作跟hash计算索引有关
// 在 HashMap 中,索引的计算方法为 (n - 1) & hash
// 所以,在进行扩容操作 (n*2) 后,该计算结果可能导致变更
// 例如
// 有一个值为 111001 的 hash
// 扩容前 n=16(10000) n-1=15(1111) (n - 1) & hash = 1111 & 111001= 001001
// 扩容后 n=32(100000) n-1=31(11111) (n - 1) & hash = 11111 & 111001= 011001
// 假如 hash 值为 101001
// 那么会发现扩容前 1111 & 101001 = 001001
// 扩容后 11111 & 101001 = 001001
// 所以可知,在进行扩容操作时,主要按照 hash 与 原数组长度中1的对应位置有关
// 如果 hash 中对应的位置为0,扩容后索引结果不变
// 不为0,表示索引结果为原结果+原数组长度
// 而 hash 中该对应位置的值只存在俩种可能 0,1
// 所以在该节点中的数据大约有一半索引不变,一半为原索引+原数组长度
// 通过 e.hash & oldCap 的方式可以得知 hash 在 oldCap 1对应的位置是否为0或1
if ((e.hash & oldCap) == 0) {
// 如果为0,证明扩容后索引的计算依然与扩容前一致
// 组装链表
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
//如果不为0,则表明扩容后索引的计算依然与扩容不一致,所以需要移动到新索引,新索引的位置为旧索引加oldCap
// 组装链表
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 如果链表不为 null,设置到新数组中
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}