学习HashMap源码
学习源码时参考视频为JDK8的HashMap
学习时心得和思考(2020.3.29)
public HashMap(int initialCapacity, float loadFactor) {
// 判断初始化容量 initialCapacity 是否小于0
if (initialCapacity < 0) {
// 如果小于 0,抛出非法的参数异常
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
}
// 判断初始化容量 initialCapacity 是否大于集合的最大容量 MAXIMUM_CAPACITY
if (initialCapacity > MAXIMUM_CAPACITY) {
// 如果超过最大容量,将最大容量赋值给 initialCapacity
initialCapacity = MAXIMUM_CAPACITY;
}
// 判断加载因子 是否小于等于0,或者是否是一个非法数值
if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
// 如果满足上面条件,抛出非法参数异常
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
}
// 将指定的负载因子赋值给 loadFactor
this.loadFactor = loadFactor;
/*
tableSizeFor 变为比指定容量大的最小的2的n次幂。
但是注意,这里计算出初始化容量之后,直接赋值给了threshold
有人认为这是个bug
事实上,在put方法中,会对threshold重新计算
*/
this.threshold = tableSizeFor(initialCapacity);
源码中是将自定义容量直接调用tableSizeFor(),然后计算出离这个数最近的且大于等于这个数的2的N次幂
并没有先进行判断此数字是否为2的n次幂
个人思考1
由于此前只判断了是否小于0.
那么 当此数字为0时
进行tableSizeFor操作
0-1=-1
计算机中任何数字都是二进制存储 -1的补码为
11111111 11111111 11111111 11111111
此数字进行
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
结果还为-1、
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
所以返回1;
所以 为啥不直接在构造方法里进行非零判断。反而调用这个方法,不浪费时间吗?
思考2
为何不先判断数字是否为2的n次幂然后再调用方法?
思考这个问题时候就在思考
怎么判断一个数字是不是2的n次幂
然后就想到一种解法:
(n&(n-1))==0;
经检验
int n = 2;
System.out.println((n&(n-1))==0);
n= 3;
System.out.println((n&(n-1))==0);
n= 5;
System.out.println((n&(n-1))==0);
n= 6;
System.out.println((n&(n-1))==0);
n= 8;
System.out.println((n&(n-1))==0);
n= 0;
System.out.println((n&(n-1))==0);
true
false
false
false
true
true
解法可行,但是要先判断是否大于0。
JDK1.8前 数组+链表
JDK1.8开始 数组+链表+红黑树
HashMap<String, Integer> map = new HashMap<>();
JDK1.8前 在创建HashMap对象后,底层创建一个长度16的Entry[] table 数组
JDK1.8后 创建HashMap对象时 底层不创建数组.
在首次调用put()方法时,底层创建一个长度16的Node[] table 数组
/**
* JDK7中叫Entry。Hash桶是一个Node数组,每个元素都是个Node链表
* 当链表长度大于8时,就会转为红黑树。小于6时,会转回链表
*/
static class Node<K, V> implements Map.Entry<K, V> {
final int hash;
final K key;
V value;
// 下一个节点
Node<K, V> next;
Node(int hash, K key, V value, Node<K, V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
@Override
public final K getKey() {
return key;
}
@Override
public final V getValue() {
return value;
}
@Override
public final String toString() {
return key + "=" + value;
}
@Override
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
@Override
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
@Override
public final boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof Map.Entry) {
Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue())) {
return true;
}
}
return false;
}
}
默认创建时数组未初始化, 初次put()时将数组扩容至16
size
size表示HashMap中存放KV的数量(为链表和树中的KV的总和)。
capacity
capacity译为容量。capacity就是指HashMap中桶的数量。默认值为16。一般第一次扩容时会扩容到64,之后好像是2倍。总之,容量都是2的幂。
loadFactor
loadFactor译为装载因子。装载因子用来衡量HashMap满的程度。loadFactor的默认值为0.75f。计算HashMap的实时装载因子的方法为:size/capacity,而不是占用桶的数量去除以capacity。
threshold
threshold表示当HashMap的size大于threshold时会执行resize操作。
threshold=capacity*loadFactor
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;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
存放数据时 调用 key对应类型的(String类)中的hashCode()方法获取哈希码值
标记一下
Object类中的hashCode()方法
底层是其他语言编写的函数
暂不记录 以后学会了搞懂了回来填坑
//Object类 底层是其他语言编写的函数
public native int hashCode();
//String类
private int hash;
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
获取到哈希码值
根据规定好的hash方法计算出存放位置在数组中对应的下标
对于该hash方法的实现:
对key的hashCode结果 (哈希码值)进行无符号右移16位做异或运算
static final int hash(Object key) {
int h;
/*
如果key为null
可以看到当key为null的时候也是有哈希值的,返回值是0
如果key不为null
首先计算出key的hashCode,然后赋值给h,接着,h进行无符号右移16位,再进行异或运算
*/
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
判断
在数组中找到对应位置进行判空 如果空则直接添加至该位置
注意 这部分的代码为 p = tab[i = (n - 1) & hash]
当数组长度为2的N次幂时,hash&n(数组长度)== hash % n(数组长度)
注意 数组长度不为2的N次幂时 效率低下 存储不均匀 降低性能 数组下标二进制末尾为1的空间都不会被使用。
transient Node<K,V>[] table;
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;
if ((tab = table) == null || (n = tab.length) == 0)
//resize是扩容方法,当当前数组为空时创建一个默认长度16的数组
n = (tab = resize()).length;
//如果key经过hash后得出来的数组下标在数组对应的值中为空,直接传值给该位置
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
不为空则产生哈希冲突(哈希碰撞)
若新key值内容和原key内容相同则替换value
若不同则在该位置下链接一个链表节点,将内容传至节点内
注意 数组+链表+红黑树中
链表是单链表
链表阈值(边界值)最大为8(最长为8个节点)
注意 当链表长度超过8 且数组长度超过64时 会转化为红黑树
注意 解决哈希碰撞方法
JDK1.8前 链表
JDK1.8开始链表+红黑树
注意 两个键的hashCode相同时 用equals比较内容,相同则替换value ,不同则添加新链表节点
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;
}
}
存放成功后比较临界值和size 相等则扩容 扩容后的容量是之前HashMap的容量的两倍
注意 开发过程中如果对效率要求较高应该避免HashMap的扩容
关于扩容我学完学懂了再总结(3.27)
扩容学完了,代码和分析在下方(3.29)
填坑扩容
本来想简单概括流程,但是失败了
根据视频注释了关键代码,看一看应该看得懂 看不懂私信我
/**
* 数组扩容
*/
final Node<K, V>[] resize() {
// 先拿到旧的hash桶
Node<K, V>[] oldTab = table;
// 获取未扩容前的数组容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 旧的临界值
int oldThr = threshold;
// 定义新的容量和临界值
int newCap, newThr = 0;
// 旧容量大于0
if (oldCap > 0) {
// 旧的容量如果超过了最大容量
if (oldCap >= MAXIMUM_CAPACITY) {
// 临界值就等于Integer类型最大值
threshold = Integer.MAX_VALUE;
// 不扩容,直接返回就数组
return oldTab;
}
/*
没超过最大值,数组扩容为原来的2倍
1.(newCap = oldCap << 1) < MAXIMUM_CAPACITY 扩大到2倍之后赋值给newCap,判断newCap是否小于最大容量
2.oldCap >= DEFAULT_INITIAL_CAPACITY 原数组长度大于等于数组初始化长度
*/
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY) {
// 当前容量在默认值和最大值的一半之间
// 新的临界值为当前临界值的2倍
newThr = oldThr << 1; // double threshold
}
} else if (oldThr > 0) // initial capacity was placed in threshold
{
// 旧容量为0,当前临界值不为0,让新的临界值等于当前临界值
newCap = oldThr;
} else {
// 当前容量和临界值都为0,让新的容量等于默认值,临界值=初始容量*加载因子
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int) (DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 经过上面对新临界值的计算后如果还是0
if (newThr == 0) {
// 计算临界值为新容量 * 加载因子
float ft = (float) newCap * loadFactor;
// 判断新容量小于最大值,并且计算出的临界值也小于最大值
// 那么就把计算出的临界值赋值给新临界值。否则新临界值默认为Integer最大值
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float) MAXIMUM_CAPACITY ?
(int) ft : Integer.MAX_VALUE);
}
// 临界值赋值
threshold = newThr;
@SuppressWarnings({"rawtypes", "unchecked"})
// 使用新的容量创建新数组
Node<K, V>[] newTab = (Node<K, V>[]) new Node[newCap];
// 赋值给hash桶
table = newTab;
// 下面一堆是复制值
// 如果旧的桶不为空
if (oldTab != null) {
// 遍历旧桶,把旧桶中的元素重新计算下标位置,赋值给新桶
// j 表示数组下标位置
for (int j = 0; j < oldCap; ++j) {
Node<K, V> e;
/*
(e = oldTab[j]) != null 将旧桶的当前下标位置元素赋值给e,并且e不为null
*/
if ((e = oldTab[j]) != null) {
// 置空,置空之后原本的这个数据就可以被gc回收
oldTab[j] = null;
// 下一个节点如果为空
if (e.next == null) {
// 如果没有下一个节点,说明不是链表,当前桶上只有一个键值对,直接计算下标后插入
newTab[e.hash & (newCap - 1)] = e;
} else if (e instanceof TreeNode) {
// 节点是红黑树,进行切割操作
((TreeNode<K, V>) e).split(this, newTab, j, oldCap);
} else { // preserve order
// 到这里说明该位置的元素是链表
/*
loHead:链表头结点
loTail:数据链表
hiHead:新位置链表头结点
hiTail:新位置数据链表
*/
Node<K, V> loHead = null, loTail = null;
Node<K, V> hiHead = null, hiTail = null;
Node<K, V> next;
// 循环链表,直到链表末再无节点
do {
// 获取下一个节点
next = e.next;
// 如果这里为true,说明e这个节点在resize之后不需要移动位置
if ((e.hash & oldCap) == 0) {
if (loTail != null) {
loTail.next = e;
} else {
loHead = e;
}
loTail = e;
} else {
if (hiTail == null) {
hiHead = e;
} else {
hiTail.next = e;
}
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
private static final long serialVersionUID = 362498820763181265L;
/**
* 默认的初始容量 ,=1<<4=16。HashMap的容量必须是2的n次幂
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
/**
* 最大容量,=1<<30
* 二进制表示就是第31位是1.后面全都是0
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默认负载因子,=0.75。与扩容有关。
* 当HashMap中元素的个数 >= 数组长度 * 负载因子
* 就会扩容数组
* 负载因子在使用的过程中,不建议改变
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 使用TreeNode的临界值,默认=8
* 经过大量的计算得知,链表中元素复合泊松分布
* 0: 0.60653066
* 1: 0.30326533
* 2: 0.07581633
* 3: 0.01263606
* 4: 0.00157952
* 5: 0.00015795
* 6: 0.00001316
* 7: 0.00000094
* 8: 0.00000006
* 上面是链表中,每个节点可能会存放元素的概率
* <p>
* 网上还有另一种说法,红黑树的平均查找长度是log(n),如果长度为8,平均查找长度是log(8) = 3
* 链表平均查找长度是 n/2,如果长度是8的情况下,8/2=4,效率低于红黑树,所以需要转换为红黑树。
* 如果链表长度小于等于6, 6/2=3.而log(6) ≈ 2.6,虽然比链表快,但是效率差距并不大
* 而且,链表转换为红黑树也需要一定的时间,所以这时候并不会转换为红黑树
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 链表值小于6会从红黑树转回链表
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 当数组长度大于这个数时才会转红黑树,否则只是扩容
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* 实际存储的数组 Entry数组。jdk中称其为 hash桶
*/
transient Node<K, V>[] table;
/**
* 缓存,存放具体元素的集合
*/
transient Set<Entry<K, V>> entrySet;
/**
* 实际存储的个数
*/
transient int size;
/**
* map中数据改变次数的统计
* 每次扩容或者更改map结构的计数器
*/
transient int modCount;
/**
* 临界值,与HashMap扩容相关
* 计算方式:数组长度 * 负载因子
* 当HashMap中元素个数超过这个值的时候
* 就会进行扩容
*
* @serial
*/
int threshold;
/**
* 负载因子,初始值=0.75,与扩容有关
*
* @serial
*/
final float loadFactor;
创建 HashMap时可以自定义容量,比如10 ,如果这个数字不是2的n次幂,HashMap会通过tableSizeFor方法获取大于这个数字且离这个数字最近的一个是2的n次幂的数,然后把这个2的n次幂作为HashMap的容量。
/**
* 该方法作用是让HashMap的容量永远是2的n次幂
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
// | (位或运算符)运算规则:两个数都转为二进制,然后从高位开始比较,两个数只要有一个为1则为1,否则就为0。
/*
>>> 表示符号位也会跟着移动,比如 -1 的最高位是1,表示是个负数,然后右移之后,最高位就是0表示当前是个正数。
所以 -1 >>>1 = 2147483647
>> 表示无符号右移,也就是符号位不变。那么-1 无论移动多少次都是-1
原理就是将最高位 1 右边的所有比特位全置为 1,然后再加 1,最高位进 1,右边的比特位全变成 0,从而得出一个 2 的次幂的值
*/
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
/**
* 用指定的容量和负载因子初始化一个HashMap
*
* @param initialCapacity 初始值
* @param loadFactor 负载因子
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public HashMap(int initialCapacity, float loadFactor) {
// 判断初始化容量 initialCapacity 是否小于0
if (initialCapacity < 0) {
// 如果小于 0,抛出非法的参数异常
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
}
// 判断初始化容量 initialCapacity 是否大于集合的最大容量 MAXIMUM_CAPACITY
if (initialCapacity > MAXIMUM_CAPACITY) {
// 如果超过最大容量,将最大容量赋值给 initialCapacity
initialCapacity = MAXIMUM_CAPACITY;
}
// 判断加载因子 是否小于等于0,或者是否是一个非法数值
if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
// 如果满足上面条件,抛出非法参数异常
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
}
// 将指定的负载因子赋值给 loadFactor
this.loadFactor = loadFactor;
/*
tableSizeFor 变为比指定容量大的最小的2的n次幂。
但是注意,这里计算出初始化容量之后,直接赋值给了threshold
有人认为这是个bug
事实上,在put方法中,会对threshold重新计算
*/
this.threshold = tableSizeFor(initialCapacity);
}
/**
* 指定容量去初始化一个HashMap
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 用默认的容量去初始化一个HashMap(16)
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
/**
* Implements Map.putAll and Map constructor.
*
* @param m the map
* @param evict false when initially constructing this map, else
* true (relayed to method afterNodeInsertion).
*/
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
// 获取map的元素个数
int s = m.size();
if (s > 0) {
// 判断 table是否已经初始化
if (table == null) {
// 未初始化, s是m的元素个数
/*
假设 s 是 6,s / loadFactor = 8
*/
float ft = ((float) s / loadFactor) + 1.0F;
int t = ((ft < (float) MAXIMUM_CAPACITY) ?
(int) ft : MAXIMUM_CAPACITY);
// 判断得到的值是否大于阈值,如果大于阈值,则初始化阈值
if (t > threshold) {
threshold = tableSizeFor(t);
}
} else if (s > threshold) {
// 已初始化,并且元素个数大于阈值,进行扩容
resize();
}
// 将m中所有的元素添加到HashMap中
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
final Node<K, V> getNode(int hash, Object key) {
Node<K, V>[] tab;
// first存放对应下标位置的第一个元素
Node<K, V> first, e;
int n;
K k;
/*
1.(tab = table) != null 把table赋值给tab,并且判断tab不为空
2.(n = tab.length) > 0 把tab的长度赋值给n,并且判断n大于0
3.(first = tab[(n - 1) & hash]) != null 根据传进来的hash计算下标位置,取出该下标位置的元素赋值给first,并且判断first不为空
*/
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 下标位置第一个元素的key就是我们要找的key
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k)))) {
return first;
}
// 获取下一个节点赋值给e,并且判断e不为空
if ((e = first.next) != null) {
if (first instanceof TreeNode) {
// 如果是红黑树,就用红黑树方式取值
return ((TreeNode<K, V>) first).getTreeNode(hash, key);
}
// 遍历链表直到下一个节点不存在为止
do {
// 找到对应的key的位置
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
return e;
}
} while ((e = e.next) != null);
}
}
return null;
}
@Override
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods.
*
* @param hash key的hash值
* @param key 原始key
* @param value key对应的value
* @param onlyIfAbsent 如果为true代表不更改现有的值
* @param evict 如果为false,表示table为创建状态
* @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;
// n存放数组长度。i存放key的hash计算后的值
int n, i;
/*
判断table是否为空
1. table 表示存储在Map中的元素的数组
2. (tab = table) == null 表示将table赋值给tab,并且判断tab是否为null。
3. (n = tab.length) == 0 表示,将tab的长度赋值给n,并判断n 是否等于-
*/
if ((tab = table) == null || (n = tab.length) == 0) {
// 如果为空就通过resize实例化一个数组
/*
这里的代码等价于
tab = resize();
n = tab.length
*/
n = (tab = resize()).length;
}
/*
i = hash & (n - 1) 计算当前key所在下标,确定在哪个桶中,并将下标赋值给i
p = tab(i) 将该位置的元素赋值给p,并且判断是否为null
*/
if ((p = tab[i = (n - 1) & hash]) == null) {
// 直接创建一个Node元素,赋值给当前下标位置
tab[i] = newNode(hash, key, value, null);
} else {
// 当前下标位置不为null
// 注意,我们在上面的if中,已经把当前下标位置的元素,赋值给了p
Node<K, V> e;
K k;
/*
比较桶中第一个元素的hash值和key是否相等。
1. p.hash == hash :判断第一个元素的hash与我们传进来的hash是否相等
2. ((k = p.key) == key || (key != null && key.equals(k)))
2.1 (k = p.key) == key 将第一个元素的key赋值给k,并且判断是否和我们传进来的key相等
2.2 判断我们传进来的key不等于null,并且key的值和k相等
上面如果都满足的情况下,说明第一个元素的key和我们传进来的key值是相等的
*/
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k)))) {
// 将该位置的节点赋值给e
e = p;
} else if (p instanceof TreeNode) {
// 判断当前下标位置的数据类型是否为红黑树
e = ((TreeNode<K, V>) p).putTreeVal(this, tab, hash, key, value);
} else {
// 说明当前元素是个链表
// 不是红黑树,当前下标位置的key也与要插入的key不相等
// 遍历链表
for (int binCount = 0; ; ++binCount) {
/*
(e = p.next) == null 将p的下一个元素赋值给e,并判断e是否为null
如果等于null,说明当前元素是表尾,已经没有下一个元素了
如果不为null,说明下一个元素还存在,可以继续遍历
*/
if ((e = p.next) == null) {
// 进入,说明e是表尾
// 直接将数据写到下一个节点
p.next = newNode(hash, key, value, null);
/*
1. 节点添加完成之后判断此时节点个数是否大于临界值 8,如果大于则将链表转为红黑树。
2. int binCount = 0,表示for循环的初始化值,从0开始计算,记录遍历节点的个数
|- 0表示第一个节点
|- 1表示第二个节点
|- 。。。。
|- 7表示第八个节点
因此这里TREEIFY_THRESHOLD需要-1
*/
if (binCount >= TREEIFY_THRESHOLD - 1) {
// 将链表转为红黑树
treeifyBin(tab, hash);
}
break;
}
// 如果当前位置的key与要存放位置的key相同,直接跳出
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
/*
要添加的元素和链表中存在的元素相等了,则跳出for循环,不需要再比较后面的元素了
直接进入下面的if语句去替换e的值
*/
break;
}
// 说明新添加的元素和当前节点不相同,继续找下一个元素。
p = e;
}
}
// e不为空,说明上面找到了一个去存储Key-Value的Node
if (e != null) {
// 拿到旧Value
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null) {
// 新的值赋值给节点
e.value = value;
}
afterNodeAccess(e);
// 返回旧value
return oldValue;
}
}
// 统计数据改变次数
++modCount;
// 当最后一次调整之后的Size大于临界值,就需要调整数组容量
if (++size > threshold) {
resize();
}
afterNodeInsertion(evict);
return null;
}
/**
* 替换指定哈希表的所引出桶中的所有节点,除非表太小,否则将修改大小,
*/
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();
} else if ((e = tab[index = (n - 1) & hash]) != null) {
/*
1.执行到这里说明哈希表中数组长度大于阈值64,开始进行树形化。
2.(e = tab[index = (n - 1) & hash]) != null 通过当前key的hash计算当前key所在的下标位置,取出来赋值给e,判断e不为空
*/
// hd:红黑树的头结点。tl:红黑树的尾结点
TreeNode<K, V> hd = null, tl = null;
do {
// 重新创建一个树节点,内容和当前链表节点e一致
TreeNode<K, V> p = replacementTreeNode(e, null);
if (tl == null) {
// 将新创建的p节点赋值给红黑树的头结点
hd = p;
} else {
/*
p.prev = tl 将上一个节点p赋值给现在的p的前一个节点
tl.next = p 将现在的节点p作为树的为节点的下一个节点
*/
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
/*
让桶中第一个元素即数组中的元素指向新建的红黑树的节点,以后这个桶里的元素就是红黑树,而不是链表
*/
if ((tab[index] = hd) != null) {
hd.treeify(tab);
}
}
}
/**
* 根据key删除元素
* 删除是有返回值的
* 并且返回值是被删除key所对应的value
*/
@Override
public V remove(Object key) {
Node<K, V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
/**
* 删除方法的核心逻辑
*
* @param hash hash for key
* @param key the key
* @param value the value to match if matchValue, else ignored
* @param matchValue if true only remove if value is equal
* @param movable if false do not move other nodes while removing
* @return the node, or null if none
*/
final Node<K, V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K, V>[] tab;
Node<K, V> p;
int n, index;
/*
1. (tab = table) != null 把hash桶赋值给tab,并且判断tab是否为nul
2. (n = tab.length) > 0 获取tab的长度,赋值给n,判断n是否大于0
3. (p = tab[index = (n - 1) & hash]) != null 根据hash计算索引位置,赋值给index
并从tab中取出该位置的元素,赋值给p,并判断,p不为null
*/
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
// 进入这里面,说明hash桶不为空,并且当前key所在位置的元素不为空
Node<K, V> node = null, e;
K k;
V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k)))) {
// 当前第一个位置的元素就是我们要找的元素
node = p;
}
// 取出p的下一个节点赋值给e,并且e不为空
else if ((e = p.next) != null) {
if (p instanceof TreeNode) {
node = ((TreeNode<K, V>) p).getTreeNode(hash, key);
} else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
// 判断node不为空,
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode) {
((TreeNode<K, V>) node).removeTreeNode(this, tab, movable);
} else if (node == p) {
// node==p,说明node是第一个节点,那么直接将下一个节点赋值给当前下标
tab[index] = node.next;
} else {
p.next = node.next;
}
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
/**
* Removes all of the mappings from this map.
* The map will be empty after this call returns.
*/
@Override
public void clear() {
Node<K, V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i) {
tab[i] = null;
}
}
}
/**
* 红黑树节点
*/
static final class TreeNode<K, V> extends LinkedHashMap.Entry<K, V> {
TreeNode<K, V> parent; // 父节点
TreeNode<K, V> left; // 左节点
TreeNode<K, V> right; // 右节点
TreeNode<K, V> prev; // needed to unlink next upon deletion
boolean red; // 节点颜色
TreeNode(int hash, K key, V val, Node<K, V> next) {
super(hash, key, val, next);
}
/**
* Returns root of tree containing this node.
*/
final TreeNode<K, V> root() {
for (TreeNode<K, V> r = this, p; ; ) {
if ((p = r.parent) == null) {
return r;
}
r = p;
}
}
/**
* Ensures that the given root is the first node of its bin.
*/
static <K, V> void moveRootToFront(Node<K, V>[] tab, TreeNode<K, V> root) {
int n;
if (root != null && tab != null && (n = tab.length) > 0) {
int index = (n - 1) & root.hash;
TreeNode<K, V> first = (TreeNode<K, V>) tab[index];
if (root != first) {
Node<K, V> rn;
tab[index] = root;
TreeNode<K, V> rp = root.prev;
if ((rn = root.next) != null) {
((TreeNode<K, V>) rn).prev = rp;
}
if (rp != null) {
rp.next = rn;
}
if (first != null) {
first.prev = root;
}
root.next = first;
root.prev = null;
}
assert checkInvariants(root);
}
}
/**
* Finds the node starting at root p with the given hash and key.
* The kc argument caches comparableClassFor(key) upon first use
* comparing keys.
*/
final TreeNode<K, V> find(int h, Object k, Class<?> kc) {
TreeNode<K, V> p = this;
do {
int ph, dir;
K pk;
TreeNode<K, V> pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h) {
p = pl;
} else if (ph < h) {
p = pr;
} else if ((pk = p.key) == k || (k != null && k.equals(pk))) {
return p;
} else if (pl == null) {
p = pr;
} else if (pr == null) {
p = pl;
} else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0) {
p = (dir < 0) ? pl : pr;
} else if ((q = pr.find(h, k, kc)) != null) {
return q;
} else {
p = pl;
}
} while (p != null);
return null;
}
/**
* Calls find for root node.
*/
final TreeNode<K, V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
/**
* Tie-breaking utility for ordering insertions when equal
* hashCodes and non-comparable. We don't require a total
* order, just a consistent insertion rule to maintain
* equivalence across rebalancings. Tie-breaking further than
* necessary simplifies testing a bit.
*/
static int tieBreakOrder(Object a, Object b) {
int d;
if (a == null || b == null ||
(d = a.getClass().getName().
compareTo(b.getClass().getName())) == 0) {
d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
-1 : 1);
}
return d;
}
/**
* Forms tree of the nodes linked from this node.
*/
final void treeify(Node<K, V>[] tab) {
TreeNode<K, V> root = null;
for (TreeNode<K, V> x = this, next; x != null; x = next) {
next = (TreeNode<K, V>) x.next;
x.left = x.right = null;
if (root == null) {
x.parent = null;
x.red = false;
root = x;
} else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
for (TreeNode<K, V> p = root; ; ) {
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h) {
dir = -1;
} else if (ph < h) {
dir = 1;
} else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
dir = tieBreakOrder(k, pk);
}
TreeNode<K, V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0) {
xp.left = x;
} else {
xp.right = x;
}
root = balanceInsertion(root, x);
break;
}
}
}
}
moveRootToFront(tab, root);
}
/**
* Returns a list of non-TreeNodes replacing those linked from
* this node.
*/
final Node<K, V> untreeify(HashMap<K, V> map) {
Node<K, V> hd = null, tl = null;
for (Node<K, V> q = this; q != null; q = q.next) {
Node<K, V> p = map.replacementNode(q, null);
if (tl == null) {
hd = p;
} else {
tl.next = p;
}
tl = p;
}
return hd;
}
/**
* Tree version of putVal.
*/
final TreeNode<K, V> putTreeVal(HashMap<K, V> map, Node<K, V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K, V> root = (parent != null) ? root() : this;
for (TreeNode<K, V> p = root; ; ) {
int dir, ph;
K pk;
if ((ph = p.hash) > h) {
dir = -1;
} else if (ph < h) {
dir = 1;
} else if ((pk = p.key) == k || (k != null && k.equals(pk))) {
return p;
} else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K, V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null)) {
return q;
}
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K, V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K, V> xpn = xp.next;
TreeNode<K, V> x = map.newTreeNode(h, k, v, xpn);
if (dir <= 0) {
xp.left = x;
} else {
xp.right = x;
}
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null) {
((TreeNode<K, V>) xpn).prev = x;
}
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
/**
* Removes the given node, that must be present before this call.
* This is messier than typical red-black deletion code because we
* cannot swap the contents of an interior node with a leaf
* successor that is pinned by "next" pointers that are accessible
* independently during traversal. So instead we swap the tree
* linkages. If the current tree appears to have too few nodes,
* the bin is converted back to a plain bin. (The test triggers
* somewhere between 2 and 6 nodes, depending on tree structure).
*/
final void removeTreeNode(HashMap<K, V> map, Node<K, V>[] tab,
boolean movable) {
int n;
if (tab == null || (n = tab.length) == 0) {
return;
}
int index = (n - 1) & hash;
TreeNode<K, V> first = (TreeNode<K, V>) tab[index], root = first, rl;
TreeNode<K, V> succ = (TreeNode<K, V>) next, pred = prev;
if (pred == null) {
tab[index] = first = succ;
} else {
pred.next = succ;
}
if (succ != null) {
succ.prev = pred;
}
if (first == null) {
return;
}
if (root.parent != null) {
root = root.root();
}
if (root == null
|| (movable
&& (root.right == null
|| (rl = root.left) == null
|| rl.left == null))) {
tab[index] = first.untreeify(map); // too small
return;
}
TreeNode<K, V> p = this, pl = left, pr = right, replacement;
if (pl != null && pr != null) {
TreeNode<K, V> s = pr, sl;
while ((sl = s.left) != null) // find successor
{
s = sl;
}
boolean c = s.red;
s.red = p.red;
p.red = c; // swap colors
TreeNode<K, V> sr = s.right;
TreeNode<K, V> pp = p.parent;
if (s == pr) { // p was s's direct parent
p.parent = s;
s.right = p;
} else {
TreeNode<K, V> sp = s.parent;
if ((p.parent = sp) != null) {
if (s == sp.left) {
sp.left = p;
} else {
sp.right = p;
}
}
if ((s.right = pr) != null) {
pr.parent = s;
}
}
p.left = null;
if ((p.right = sr) != null) {
sr.parent = p;
}
if ((s.left = pl) != null) {
pl.parent = s;
}
if ((s.parent = pp) == null) {
root = s;
} else if (p == pp.left) {
pp.left = s;
} else {
pp.right = s;
}
if (sr != null) {
replacement = sr;
} else {
replacement = p;
}
} else if (pl != null) {
replacement = pl;
} else if (pr != null) {
replacement = pr;
} else {
replacement = p;
}
if (replacement != p) {
TreeNode<K, V> pp = replacement.parent = p.parent;
if (pp == null) {
root = replacement;
} else if (p == pp.left) {
pp.left = replacement;
} else {
pp.right = replacement;
}
p.left = p.right = p.parent = null;
}
TreeNode<K, V> r = p.red ? root : balanceDeletion(root, replacement);
if (replacement == p) { // detach
TreeNode<K, V> pp = p.parent;
p.parent = null;
if (pp != null) {
if (p == pp.left) {
pp.left = null;
} else if (p == pp.right) {
pp.right = null;
}
}
}
if (movable) {
moveRootToFront(tab, r);
}
}
/**
* Splits nodes in a tree bin into lower and upper tree bins,
* or untreeifies if now too small. Called only from resize;
* see above discussion about split bits and indices.
*
* @param map the map
* @param tab the table for recording bin heads
* @param index the index of the table being split
* @param bit the bit of hash to split on
*/
final void split(HashMap<K, V> map, Node<K, V>[] tab, int index, int bit) {
TreeNode<K, V> b = this;
// Relink into lo and hi lists, preserving order
TreeNode<K, V> loHead = null, loTail = null;
TreeNode<K, V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
for (TreeNode<K, V> e = b, next; e != null; e = next) {
next = (TreeNode<K, V>) e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null) {
loHead = e;
} else {
loTail.next = e;
}
loTail = e;
++lc;
} else {
if ((e.prev = hiTail) == null) {
hiHead = e;
} else {
hiTail.next = e;
}
hiTail = e;
++hc;
}
}
if (loHead != null) {
if (lc <= UNTREEIFY_THRESHOLD) {
tab[index] = loHead.untreeify(map);
} else {
tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
{
loHead.treeify(tab);
}
}
}
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD) {
tab[index + bit] = hiHead.untreeify(map);
} else {
tab[index + bit] = hiHead;
if (loHead != null) {
hiHead.treeify(tab);
}
}
}
}
/* ------------------------------------------------------------ */
// Red-black tree methods, all adapted from CLR
static <K, V> TreeNode<K, V> rotateLeft(TreeNode<K, V> root,
TreeNode<K, V> p) {
TreeNode<K, V> r, pp, rl;
if (p != null && (r = p.right) != null) {
if ((rl = p.right = r.left) != null) {
rl.parent = p;
}
if ((pp = r.parent = p.parent) == null) {
(root = r).red = false;
} else if (pp.left == p) {
pp.left = r;
} else {
pp.right = r;
}
r.left = p;
p.parent = r;
}
return root;
}
static <K, V> TreeNode<K, V> rotateRight(TreeNode<K, V> root,
TreeNode<K, V> p) {
TreeNode<K, V> l, pp, lr;
if (p != null && (l = p.left) != null) {
if ((lr = p.left = l.right) != null) {
lr.parent = p;
}
if ((pp = l.parent = p.parent) == null) {
(root = l).red = false;
} else if (pp.right == p) {
pp.right = l;
} else {
pp.left = l;
}
l.right = p;
p.parent = l;
}
return root;
}
static <K, V> TreeNode<K, V> balanceInsertion(TreeNode<K, V> root,
TreeNode<K, V> x) {
x.red = true;
for (TreeNode<K, V> xp, xpp, xppl, xppr; ; ) {
if ((xp = x.parent) == null) {
x.red = false;
return x;
} else if (!xp.red || (xpp = xp.parent) == null) {
return root;
}
if (xp == (xppl = xpp.left)) {
if ((xppr = xpp.right) != null && xppr.red) {
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
} else {
if (x == xp.right) {
root = rotateLeft(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateRight(root, xpp);
}
}
}
} else {
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
} else {
if (x == xp.left) {
root = rotateRight(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateLeft(root, xpp);
}
}
}
}
}
}
static <K, V> TreeNode<K, V> balanceDeletion(TreeNode<K, V> root,
TreeNode<K, V> x) {
for (TreeNode<K, V> xp, xpl, xpr; ; ) {
if (x == null || x == root) {
return root;
} else if ((xp = x.parent) == null) {
x.red = false;
return x;
} else if (x.red) {
x.red = false;
return root;
} else if ((xpl = xp.left) == x) {
if ((xpr = xp.right) != null && xpr.red) {
xpr.red = false;
xp.red = true;
root = rotateLeft(root, xp);
xpr = (xp = x.parent) == null ? null : xp.right;
}
if (xpr == null) {
x = xp;
} else {
TreeNode<K, V> sl = xpr.left, sr = xpr.right;
if ((sr == null || !sr.red) &&
(sl == null || !sl.red)) {
xpr.red = true;
x = xp;
} else {
if (sr == null || !sr.red) {
if (sl != null) {
sl.red = false;
}
xpr.red = true;
root = rotateRight(root, xpr);
xpr = (xp = x.parent) == null ?
null : xp.right;
}
if (xpr != null) {
xpr.red = (xp == null) ? false : xp.red;
if ((sr = xpr.right) != null) {
sr.red = false;
}
}
if (xp != null) {
xp.red = false;
root = rotateLeft(root, xp);
}
x = root;
}
}
} else { // symmetric
if (xpl != null && xpl.red) {
xpl.red = false;
xp.red = true;
root = rotateRight(root, xp);
xpl = (xp = x.parent) == null ? null : xp.left;
}
if (xpl == null) {
x = xp;
} else {
TreeNode<K, V> sl = xpl.left, sr = xpl.right;
if ((sl == null || !sl.red) &&
(sr == null || !sr.red)) {
xpl.red = true;
x = xp;
} else {
if (sl == null || !sl.red) {
if (sr != null) {
sr.red = false;
}
xpl.red = true;
root = rotateLeft(root, xpl);
xpl = (xp = x.parent) == null ?
null : xp.left;
}
if (xpl != null) {
xpl.red = (xp == null) ? false : xp.red;
if ((sl = xpl.left) != null) {
sl.red = false;
}
}
if (xp != null) {
xp.red = false;
root = rotateRight(root, xp);
}
x = root;
}
}
}
}
}
/**
* Recursive invariant check
*/
static <K, V> boolean checkInvariants(TreeNode<K, V> t) {
TreeNode<K, V> tp = t.parent, tl = t.left, tr = t.right,
tb = t.prev, tn = (TreeNode<K, V>) t.next;
if (tb != null && tb.next != t) {
return false;
}
if (tn != null && tn.prev != t) {
return false;
}
if (tp != null && t != tp.left && t != tp.right) {
return false;
}
if (tl != null && (tl.parent != t || tl.hash > t.hash)) {
return false;
}
if (tr != null && (tr.parent != t || tr.hash < t.hash)) {
return false;
}
if (t.red && tl != null && tl.red && tr != null && tr.red) {
return false;
}
if (tl != null && !checkInvariants(tl)) {
return false;
}
if (tr != null && !checkInvariants(tr)) {
return false;
}
return true;
}
}