Java集合之HashMap源码篇

☆* o(≧▽≦)o *☆嗨~我是小奥🍹
📄📄📄个人博客:小奥的博客
📄📄📄CSDN:个人CSDN
📙📙📙Github:传送门
📅📅📅面经分享(牛客主页):传送门
🍹文章作者技术和水平有限,如果文中出现错误,希望大家多多指正!
📜 如果觉得内容还不错,欢迎点赞收藏关注哟! ❤️

Java集合之HashMap源码详解

概述

HashMap主要用来存放键值对,它基于哈希表的Map接口实现。HashMap的实现是不同步的,说明它不是线程安全的,它的key和value都可以为null。

  • HashMap JDK1.8之前的底层实现是 数组 + 链表,数组是存储元素的主要部分,链表则是为了解决哈希冲突。
    • 即使哈希函数选择的再好,也很难实现元素百分百均匀分布。当HashMap有大量的元素都存放到一个桶中,这个桶有一个很长的链表,极端情况下HashMap就相当于一条链表,遍历的时间复杂度是O(n),这就完全失去了它的优势。
  • HashMap JDK1.8之后的底层实现是 数组 + 链表 + 红黑树,桶中的结构可能是链表也可能是红黑树。
    • 当链表长度大于阈值(或者说是红黑树的阈值,默认为8)并且当前数组的长度大于64时,此时此索引上的所有元素改为红黑树存储;当链表的结点小于6时,红黑树结构又会转化为链表结构。

HashMap通过key计算出hash值,然后通过 (n - 1) & hash判断当前元素存放的位置(n是指数组长度),如果当前位置存在元素的话,就判断与该元素要存入的元素的hash值以及key是否相同,如果相同的话,直接覆盖,如果不同就通过拉链法解决冲突。

HashMap 默认的初始化大小为 16。之后每次扩充,容量变为原来的 2 倍。并且, HashMap 总是使用 2 的幂作为哈希表的大小。

底层数据结构

  • **capacity**:目前数组的长度,值总是2^n次方的整数。每次扩容后,n会加1,即整个数组容量会扩充为之前的2倍,该初始值默认值为16。

  • **loadFactor**:负载因子,默认为0.75。

  • **threshold*:扩容的阈值,等于capacityloadFactor,即当数组内达到这么多元素时,会触发扩容。

    默认的负载因子0.75是对空间和时间效率的一个平衡选择,一般建议不要修改。如果内存空间多而又对时间效率要求很高,可以降低负载因子的值;相反,如果内存空间紧张而对时间效率要求不高,可以增加负载因子的值,这个值可以大于1。

  • **Node**:数组中元素的数据结构,包含四个属性:hash、key、value和next。

  • **table**:存储节点的数组。

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
// 序列号
private static final long serialVersionUID = 362498820763181265L;
// 默认的初始容量是16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认的负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 当桶(bucket)上的结点数大于等于这个值时会转成红黑树
static final int TREEIFY_THRESHOLD = 8;
// 当桶(bucket)上的结点数小于等于这个值时树转链表
static final int UNTREEIFY_THRESHOLD = 6;
// 桶中结构转化为红黑树对应的table的最小容量
static final int MIN_TREEIFY_CAPACITY = 64;
// 存储元素的数组,总是2的幂次倍
transient Node<k,v>[] table;
// 存放具体元素的集
transient Set<map.entry<k,v>> entrySet;
// 存放元素的个数,注意这个不等于数组的长度。
transient int size;
// 每次扩容和更改map结构的计数器
transient int modCount;
// 阈值(容量*负载因子) 当实际大小超过阈值时,会进行扩容
int threshold;
// 负载因子
final float loadFactor;
....
}

构造函数

  • 如果没有指定容量和负载因子大小,则容量大小默认为16,负载因子大小默认为0.75
  • 如果指定容量和负载因子大小,则
    • 首先判断指定的容量是否小于0,如果小于0,则抛出IllegalArgumentException
    • 如果指定的容量大小大于HashMap的容量极限1<<30),那么容量就等于最大容量;
    • 如果**负载因子小于0或者为NaN**,那么抛出IllegalArgumentException异常。
    • 如果都没有上面的情况,那么就指定容量和负载因子大小
/**
* 构造具有指定初始容量和负载因子的空HashMap。
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
//指定的容量大小不可以小于0,否则将抛出IllegalArgumentException异常
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//判定指定的容量大小是否大于HashMap的容量极限
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
//指定的负载因子不可以小于0或为NaN,若判定成立则抛出IllegalArgumentException异常
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
// 初始容量暂时放到threshold,在resize中再赋值给newCap进行table初始化
// 设置“HashMap阈值”,当HashMap中存储数据的数量达到threshold时,就需要将HashMap的容量加倍。
//tableSizeFor用于查找到大于给定数值的最近2次幂值,比如给定18就是32。给定33就是64
this.threshold = tableSizeFor(initialCapacity);
}

/**
* 用指定的初始值构造一个空的HashMap容量和默认负载因子(0.75)。
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
* 使用默认初始容量(16)和默认负载因子(0.75)构造一个空的HashMap。
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

/**
* 构造一个与指定Map具有相同映射的新HashMap。
* HashMap是用默认负载因子(0.75)创建的,初始容量足以在指定的Map中保存映射。
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}

扰动函数(hash)

JDK1.7
static int hash(int h) {
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}

JDK1.8
static final int hash(Object key) {
int h;
// ^ 异或 >>> 无符号右移,空位以0补齐
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

总结:相比于JDK1.8的hash方法,JDK1.7性能稍微差点,但是原理是一样的。如果key为null的时候的hash值为0,说明HashMap是支持存储null值的。

put()方法

put方法是通过putVal方法实现的,具体逻辑如下:

  • 首先获取动态数组对象和长度,若动态数组对象为空或者说是长度为0,则调用resize()扩容方法进行初始化。
  • 判断动态数组中的这个key的hash值的节点是否为空(具体做法是key的hashCode的高16位和低16位做异或运算,然后根据这个hash值去计算数组的下标位置,具体是 (capacity - 1) & hash)
    • 如果为空,则创建一个新的node节点,放入key和value。
    • 如果不为空,分为三种情况:
      • 如果动态数组的第一个元素是和key一样,则暂时存储当前的node到e中,方便后续返回oldValue;
      • 如果动态数组的第一个元素是红黑树结构,则直接在树中插入键值对;
      • 如果动态数组是链表结构,循环遍历这个链表,直到node.next为空,才会插入该key和value(在链表尾部插入)。如果插入之后链表长度大于8并且数组长度大于64才会进行树化处理。在遍历过程中,如果发现有node的key和要插入的key相同,则直接退出遍历。
    • 如果key的value不为空,用节点e设置新的value,并返回旧的value。不再进行后续操作。
  • 如果是插入节点,则继续判断当前集合容量是否达到阈值,如果达到阈值则进行扩容处理
  • 执行完这些操作,然后返回null。
 /**
* 将指定值与此映射中的指定键关联。如果映射以前包含键的映射,则替换旧值。
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

/**
* 实现了Map.put和相关方法
*/
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)
// table未初始化或者长度为0,则进行扩容
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
// (n - 1) & hash 确定元素存放在哪个桶中
// 桶为空,新生成节点放入桶中(此时,这个结点是放在数组中)
tab[i] = newNode(hash, key, value, null);
else {
// 桶中已经存在元素,处理hash冲突
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 快速判断第一个节点table[i]的key是否与插入的key一样
// 若相同则直接使用插入的p值替换掉旧的值e
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
// 如果节点数量达到阈值(默认为8),执行treeifyBin方法
// 根据HashMap数组来决定是否转换为红黑树
// 只有当数组长度大于或者等于64的情况下,才会执行红黑树操作,减少搜索次数
// 否则,只是对数组扩容
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
// 如果链表节点的key与插入元素的key相等,跳出循环
break;
// 用于遍历桶中的链表,与前面的 e = p.next组合,遍历链表
p = e;
}
}
if (e != null) { // existing mapping for key
// 在桶中找到key值、hash值与插入元素相等的节点
// 记录e的value
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
// onlyIfAbsent为false或者oldValue为null,用新值替换旧值
e.value = value;
// 访问后回调
afterNodeAccess(e);
// 返回旧值
return oldValue;
}
}
++modCount; // 结构性修改
if (++size > threshold)
// 如果实际大小大于阈值则扩容
resize();
afterNodeInsertion(evict); // 插入后回调
return null;
}

为什么数组的长度总是2的n次方?

为了让HashMap的额存取高效,尽量避免较少的碰撞,即把数据尽量分布均匀。Hash的值的范围是-2^312 ^ 31次方,只要哈希函数映射的比较松散,一般是很难出现碰撞的。但是这么大的数组,内存肯定放不下,所以实际中还要对这个数组的长度进行取模运算。

但是取模运算对计算机的开销还是比较大的,所以使用二进制运算**hash & (n - 1)**代替取模,比取模运算效率更高。

get()方法

/**
* 返回指定键映射到的值,如果此映射不包含该键的映射,则返回null。
*
* 更正式地说,如果这个映射包含一个从键k到值v的映射,
* 使得(key==null ?K ==null: key.equals(K)),则此方法返回v;否则返回null。(最多只能有一个这样的映射。)
*
* 返回值为null并不一定表示映射不包含该键的映射;也有可能映射显式地将键映射为null。
* containsKey操作可以用来区分这两种情况。
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}

/**
* 实现了Map.get相关方法
*/
final Node<K,V> getNode(int hash, Object key) {
// table:当前map的数组 first:当前hash对应索引位置上的节点 e:遍历过程中临时存储的节点
// n:table数组的长度
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
// 如果相等,直接返回
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
// 在树结构中get
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
// 在链表中get,遍历链表
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}

resize()方法

什么时候进行扩容?

  • HashMap初始化后添加元素时。HashMap创建以后并不是立即就初始化table,而是在第一次放入元素的时候,才会初始化table,这是HashMap节省内存的一种机制。而table的初始化也是resize()方法实现的。
  • 达到阈值后才会触发扩容。这个阈值,是Hash中的threshold的属性,就是容量 * 负载因子

JDK7的扩容

JDK1.7的扩容首先判断旧数组的长度是否已经达到了最大值(2^30),如果达到了那么将数组的最大容量设置为2^30-1

否则创建一个指定容量的新的数组,遍历原来的数组重新计算所有元素的索引,然后重新赋值,如果某个位置发生了哈希冲突,使用的是单链表的头插法,同一位置的新的元素总是在那个在链表的头部,这样与原来集合链表相比,扩容之后就是倒序的链表了。

//参数 newCapacity 为新数组的大小
void resize(int newCapacity) {
Entry[] oldTable = table;//引用扩容前的 Entry 数组
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {//扩容前的数组大小如果已经达到最大(2^30)了
threshold = Integer.MAX_VALUE;//修改阈值为int的最大值(2^31-1),这样以后就不会扩容了
return;
}

Entry[] newTable = new Entry[newCapacity];//初始化一个新的Entry数组
transfer(newTable, initHashSeedAsNeeded(newCapacity));//将数组元素转移到新数组里面
table = newTable;
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);//修改阈值
}
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {//遍历数组
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);//重新计算每个元素在数组中的索引位置
e.next = newTable[i];//标记下一个元素,添加是链表头添加
newTable[i] = e;//将元素放在链上
e = next;//访问下一个 Entry 链上的元素
}
}
}

JDK8的扩容

扩容的流程大致如下:

首先对三种情况进行判断:

1、情况一:若旧表的容量大于0:

  • 首先判断数组长度是否已经达到最大阈值(2^30),如果已经达到最大阈值,则不再进行扩容,将最大阈值设置为Integer.MAX_VALUE,然后将旧表返回。
  • 新表的容量的2倍小于数组的最大阈值(2^30) 并且旧表的容量大于容量默认值大小(16),则新表的阈值直接等于旧表阈值的2倍(阈值是threshold = 容量 * 负载因子)

2、情况二:若旧表的阈值大于0,则将新表容量赋值为该阈值。

3、情况三:其他情况(即HashMap的table未初始化的时候),使用默认值进行初始化

完成1、2、3之后,继续执行。

4、若新表的阈值为0,则此时计算新表的阈值,并将计算之后的阈值赋值给threshold,作为下一次扩容的判断依据。

5、通过for循环遍历将旧表的数据保存到新表

  • 如果当前节点只有一个元素,那么通过计算hash值将其放到新表正确的位置
  • 如果当前节点是红黑树类型,那么分割树,将新表和旧表分割成两个树,并判断此处索引处节点的长度是否需要转换成红黑树放入新表存储
  • 否则就按照链表的方式插入新的数据,通过do-while循环将旧数据和新数据存储到新表的指定位置。
/**
* 初始化或加倍表大小。如果为空,则按照字段阈值中持有的初始容量目标进行分配。
* 否则,由于我们使用的是2的幂展开,因此每个桶中的元素必须保持在相同的索引上,或者在新表中以2的幂偏移量移动。
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length; // 原数组如果为空,则长度赋值为0
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
// 如果原数组长度大于0,说明HashMap已经初始化过了,是一次正常的扩容
if (oldCap >= MAXIMUM_CAPACITY) {
// 判断旧的容量是否大于容量最大值(2^30),如果是,则无法扩容,那么修改阈值为 Integer.MAX_VALUE
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// // 原数组长度大于等于初始化长度16,并且原数组长度扩大1倍也小于 2^30次方,扩容为原来的2倍
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // 初始容量被置于阈值
// 如果旧容量 = 0 且 旧阈值 > 0,说明是通过构造方法创建的HashMap
// 新容量直接等于旧阈值
// 创建对象时初始化容量大小放在threshold中,此时只需要将其作为新的数组容量
newCap = oldThr;
else { // 零初始阈值表示使用默认值
// 无参构造函数创建的对象在这里计算容量和阈值
newCap = DEFAULT_INITIAL_CAPACITY; // 数组长度初始化为16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 数组阈值初始化为12
}
if (newThr == 0) {
// 创建时指定了初始化容量或者负载因子,在这里进行阈值初始化
// 或者扩容前旧容量小于16,在这里计算新的resize上限
float ft = (float)newCap * loadFactor;
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];
table = newTab;
if (oldTab != null) {
// 把每个bucket都移动到新的buckets中
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
// 当前桶位数据不为空,但是不能判断是链表还是红黑树结构
oldTab[j] = null;
if (e.next == null)
// 如果e结点不存在下一个结点,说明e是单个元素,则直接放入新数组的对应位置
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 将红黑树拆分成两棵子树,如果子树节点小于等于UNTREEIFY_THRESHOLD(默认为 6),
// 则将子树转换为链表,否则保持子树的树结构
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
// 否则e为链表,则对链表进行遍历
// 低位链表:存放在扩容之后的数组的下标位置,与当前数组下标位置一致
// loHead:低位链表头节点
// loTail低位链表尾节点
Node<K,V> loHead = null, loTail = null;
// 高位链表,存放扩容之后的数组的下标位置,=原索引+扩容之前数组容量
// hiHead:高位链表头节点
// hiTail:高位链表尾节点
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
// 通过 & 运算计算当前结点的hash值是高位为1还是0
if ((e.hash & oldCap) == 0) {
// 高位为0,放入低位链表中
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
// 高位为1,放入高位链表中
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
// 原索引放到bucket里,将低位链表头结点指向原来的索引位置
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
// 原索引+oldCap放到bucket里,将高位链表头结点指向新的索引位置
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}

HashMap面试题总结

解决Hash冲突的方式有哪些

(1)开放寻址法

这种方法也称为再散列法,其基本思想是:当关键字key的哈希地址p=H(key)出现冲突时,以p为基础,产生另外一个哈希地址p1,如果p1仍然产生冲突,再以p1为基础,产生另一个哈希地址,直到找出一个不冲突的哈希地址,将相应的元素存入其中。

Hi = (H(key) + d1) % m
其中i=1,2,3...,s, H(key)为哈希函数,m为哈希表长,di为增量序列

开放寻址法对增量di有三种取法。

(1)线性探测法。di=c * i,最简单的情况 c = 1

(2)平方探测法,也称二次探测再散列。di = 12,-12,22, -22

(3)随机探测法,di是一伪随机数列

(2)链地址法

把具有相同哈希地址的关键字的值放在同一个链表中,若选定的哈希表的长度为m,则可将哈希表定义为一个由m个头指针组成的指针数组T,凡是哈希地址为i的界定,均插入到T[i]为头结点的单链表中。T中各分量的初值均应为空。

(3)再哈希法

Hi = RHi(key) i=1,2,3,...

RHi均是不同的哈希函数,即在产生冲突时,计算另一个哈希函数地址,直到冲突不再发生。

(4)建立一个公共溢区

所有关键字和基本表中的关键字为同义词的记录,不管它们由哈希函数得到的哈希地址是什么,一旦发生冲突,都填入公共溢出表。

HashMap和Hashtable的区别

(1)线程安全:HashMap是非线程安全的,Hashtable是线程安全的。因为Hashtable内部的方法基本都经过了synchronized的修饰。(如果要保证线程安全的话可以使用ConcurrentHashMap

(2)效率:因为线程安全的问题,HashMap要比Hashtable效率高一点,另外,Hashtable基本被淘汰。

(3)对null key和null value的支持:HashMap可以存储null的key和value,但null作为键只能有一个,而value可以有多个;Hashtable不允许null键和null值,否则会抛出异常(null 键在计算hash值的时候直接会抛出空指针异常,而null值则会直接抛出空指针异常)。

(4)初始容量大小和每次扩容大小的不同

  • 创建时如果不指定容量的初始值,Hashtable默认的初始值大小为11,之后每次扩容,容量变为原来的2n + 1;HashMap默认的初始化大小为16,之后每次扩容,容量变为原来的2倍。
  • 创建时如果给定了容量的初始值,那么Hashtable会直接使用给定的大小,而HashMap则会将其扩充为2的幂次方大小。

(5)底层数据结构:jdk1.8之后的HashMap在解决哈希冲突时有了较大的变化,当链表长度大于阈值(默认为8)(将链表转换成红黑树之前会判断,如果当前数组的长度小于64,那么会选择先进行数组扩容,而不是转换为红黑树)时,将链表转为为红黑树,以减少搜索时间。而Hashtable则没有这样的机制。

HashMap和HashSet的区别

(1)实现接口:HashSet实现了Set接口,仅存储对象;而HashMap实现了Map接口,存储的是键值对。

(2)底层实现:HashSet的底层就是基于HashMap实现的,HashSet的值就是HashMap的key,HashMap的value是一个Object对象。所以HashSet不允许出现重复值,判断标准也是使用的HashMap的判断标准。

(3)效率:HashMap的效率在有的时候会比HashSet高。

HashMap和HashSet在进行存储的时候,都需要计算哈希值,但是HashMap的键的类型,通常是一个字符串或者一个简单的数字。计算该对象(String或者Integer)的哈希值比整个对象的默认的哈希值计算快的多。

所以,如果HashMap的键和HashSet的值是同一个对象,那么效率不会有太大差异,否则HashMap的效率比HashSet高。

HashMap和TreeMap的区别

(1)是否线程安全:两者都不是线程安全的。

(2)对排序的支持:HashMap不支持元素排序,而TreeMap支持根据key的顺序来排序。

(3)对NULL的支持:HashMap允许一个null key和多个null value,而TreeMap不允许null key,但是允许null value。

(4)性能区别:HashMap底层是数组实现的,所以在添加、删除和查找等方法上效率比较高,而TreeMap底层是一个红黑树结构,操作的速度比较慢。并且产生哈希冲突时,红黑树结构还要进行自平衡操作来维持树的平衡,效率比较低。

HashMap的扩容为什么是2倍

HashMap计算添加元素的位置时,使用的是位运算,使用(n-1)&hash,另外HashMap的初始容量是2的n次幂,扩容也是以2倍的方式扩容,是因为容量是2的n次幂,可以使得元素更加均匀部分在HashMap的数组上,减少hash碰撞,避免形成链表结构,使得查询效率降低。

HashMap为什么链表长度超过8才转为红黑树

虽然转化为红黑树后,查找的效率会比链表更高,但是树节点占用空间是普通节点的两倍,如果链表节点不够多却转换成红黑树,会耗费大量的空间资源。

从平均查找长度来看,红黑树的平均查找长度是logN,而链表的平均查找长度是n/2,所以阈值为8是两种数据结构效率交叉的点。比如长度为6时红黑树退化成链表,是因为两者的平均查找长度相差不大,而红黑树节点占用更多的空间。

理想情况下,在随机hash值下,加载因子为0.75的情况下,节点的频率服从参数平均为0.5的泊松分布,官方做过很多的测试,发现链表长度在大于8以后再出现hash碰撞的可能性几乎为0。

红黑树的转化、左旋右旋保持平衡还是相对耗时的,所以链表长度阈值设置为8就是为了尽量减少HashMap中出现红黑树,从而提高HashMap的效率。

HashMap为什么在数组长度大于64才会进化为红黑树

在数组比较小时如果出现红黑树结构,反而会降低效率,而红黑树需要进行左旋右旋,变色,这些操作来保持平衡,同时数组长度小于64时,搜索时间相对要快些,总之是为了加快搜索速度,提高性能。

同时官方注释规定,最小的树转化阈值应该是 4 * 链表的最大长度(也就是8),以避免调整大小阈值和树化阈值之间的冲突。

HashMap为什么加载因子设置为0.75,初始化临界值是12

官方注释:一般来说,默认的加载系数(0.75)提供了一个很好的选择时间和空间成本的权衡。较高的数值会降低空间开销,但是会增加查找成本(反映在大多数hashMap类的操作,如get、put等)。

加载因子越大,填满的元素更多,空间利用率越高,但发生冲突的几率变得更大。加载因子越小,填满的元素越少,发生冲突的几率更小,但是空间利用率更低,而且还会提高扩容rehash的次数。

而初始临界值是threshold(临界值)计算公式:capacity(数组长度默认16) * loadFactor(负载因子默认0.75) ,是HashMap衡量数组是否需要扩容的一个标准。

一般用什么作为HashMap的key

为什么Java中HashMap的key,必须要实现hashCode、equals方法? - 掘金 (juejin.cn)

从HashMap的语法上来讲,一切的对象都可以作为Key值。比如Integer、String、Object等。但是实际上来说,我们最好还是使用一些重写了HashCode()和equals()方法的类来当作HashMap的key,或者说像String这样,每次操作都会生成新的对象的类,天生线程安全的类。

HashMap为什么线程不安全出现的问题

(1)扩容导致循环链表

容器框架 - 在JDK1.7下HashMap的死循环问题 - 《初梦 ‘s 学习记录》 - 极客文档 (geekdaxue.co)

HashMap在多线程下扩容会导致链表成为环形链表,JDK1.7中HashMap使用头插法插入元素,在多线程的环境下,扩容的时候可能会导致环形链表的出现,这时如果HashMap执行get操作就会形成死循环。因此JDK1.8中使用尾插法插入元素,在扩容的时候会保持链表元素的原本顺序,不会出现环形链表的问题。

死循环如何产生的?

那就是在put操作的时候,如果size>initialCapacity*loadFactor,那么这时候HashMap就会进行rehash操作.并发下的 Rehash 会造成元素之间会形成一个循环链表。不过,jdk 1.8 后解决了这个问题,但是还是不建议在多线程下使用 HashMap,因为多线程下使用 HashMap 还是会存在其他问题比如数据丢失。

JDK1.7的resize源码如下:

void resize(int newCapacity) {   //传入新的容量
Entry[] oldTable = table; //引用扩容前的Entry数组
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) { //扩容前的数组大小如果已经达到最大(2^30)了
threshold = Integer.MAX_VALUE; //修改阈值为int的最大值(2^31-1),这样以后就不会扩容了
return;
}
Entry[] newTable = new Entry[newCapacity]; //初始化一个新的Entry数组
transfer(newTable); //!!将数据转移到新的Entry数组里
table = newTable; //HashMap的table属性引用新的Entry数组
threshold = (int) (newCapacity * loadFactor);//修改阈值
}
void transfer(Entry[] newTable) {
Entry[] src = table; //src引用了旧的Entry数组
int newCapacity = newTable.length;
for (int j = 0; j < src.length; j++) { //遍历旧的Entry数组
Entry<K, V> e = src[j]; //取得旧Entry数组的每个元素
if (e != null) {
src[j] = null;//释放旧Entry数组的对象引用(for循环后,旧的Entry数组不再引用任何对象)
do {
Entry<K, V> next = e.next;
int i = indexFor(e.hash, newCapacity); //!!重新计算每个元素在数组中的位置
e.next = newTable[i]; //标记[1]
newTable[i] = e; //将元素放在数组上
e = next; //访问下一个Entry链上的元素
} while (e != null);
}
}
}

具体过程如下:

正常rehash的过程:

假设我们的hash算法就是简单的 key mod size

最上面的时old hash表,其中hash的size = 2,所以key = 3,5,7,在mod 2 之后冲突都产生在table[1]这里

接下来hash表长度扩容为4,然后所有的key重新rehash

并发下的rehash

do {
Entry<K, V> next = e.next; // 线程1执行到此处被调度挂起
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
} while(e != null);

(1)首先假设我们有两个线程。

当线程1进行rehash时,当节点e指向key3,节点e.next指向key7,这时线程挂起,而线程2已经执行完成,于是会产生以下场景:

注意,此时线程1的节点e的指向为key3,而节点e.next指向为key7,在线程2进行rehash之后,指向了重组之后的链表(使用头插法),链表的顺序被反转。

(2)线程1被调度回来执行,先是执行 newTalbe[i] = e, 然后是e = next,导致了e指向了key(7),而下一次循环的next = e.next导致了next指向了key(3)。

e.next = newTable[i] 导致 key(3).next 指向了 key(7)。注意:此时的key(7).next 已经指向了key(3), 环形链表就这样出现了。

(2)put导致元素丢失

多线程下HashMap的put元素可能会导致元素的丢失。多线程同时执行put操作,如果计算出来的索引位置是相同的,那么可能会造成前一个key被后一个key覆盖,导致元素的丢失。这个问题在JDK1.7和JDK1.8都存在。

(3)put和get并发导致空指针

在多线程环境下,如果线程1执行put方法时,因为元素个数超过阈值而导致rehash扩容,线程2此时执行get方法,有可能会获取到null值。这个问题在JDK1.7和JDK1.8都存在。

计算hash值时为什么要让低16bit和高16bit进行异或处理

Hash值其实是一个int类型的数据,二进制为32位。而HashMap的初始容量为16,在进行hash运算的时候,hashCode & 15 ==> hashCode & 1111,这时计算的哈希值只能与第四位进行与操作,也就是说hashCode的高四位其实并没有参与运算,这样会导致很多哈希值不同而高四位有区别的数,计算出来的索引都是一样的,产生较多的哈希冲突。

为了避免这种情况,HashMap将高16位与第16位进行异或操作,这样可以保证高位的数据也能参与到hash值的计算当中,以增加索引的散列程序,让数据分布的更加均匀。

什么方法可以解决HashMap不安全

(1)通过Collections.synchronizedMap返回一个线程安全的Map。不推荐使用,因为底层维护一个锁对象,所有的操作都需要通过这个锁对象,效率比较低。

(2)使用Hashtable。Hashtable是线程安全的集合类,但是已经被废弃了。

(3)使用ConcurrentHashMap代替HashMap。ConcurrentHashMap采用分段锁思想灵活保证线程操作的安全,效率相对于直接加锁更好。

源码

package java.util;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import sun.misc.SharedSecrets;

public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {

private static final long serialVersionUID = 362498820763181265L;

/*
* 实现说明
*
* 这个映射通常作为一个binned(桶)哈希表,但是当桶变得太大时,
* 它们被转换成treenode的桶,每个节点的结构与java.util.TreeMap中的相似。
* 大多数方法尝试使用正常的桶,但在适用的情况下中继到TreeNode方法(只需通过检查节点的instanceof)。
* TreeNodes的桶可以像其他桶一样遍历和使用,但在填充过多时还支持更快的查找。
* 然而,由于绝大多数正常使用的容器都没有过度填充,因此检查树容器是否存在可能会在表方法的过程中被延迟。
*
* 树桶(即,其元素都是treenode的桶)主要由hashCode排序,但在关联的情况下,
* 如果两个元素属于相同的“类C实现Comparable<C>”,则键入它们的compareTo方法用于排序。
* (我们通过反射保守地检查泛型类型来验证这一点——参见方法comparableClassFor)。
* 当键具有不同的哈希值或可排序时,树桶增加的复杂性在提供最坏情况O(log n)操作方面是值得的,
* 因此,在意外或恶意使用hashCode()方法返回分布不佳的值以及许多键共享hashCode的情况下,
* 只要它们也是可比较的,性能就会优雅地下降。
* (如果这两项都不适用,与不采取预防措施相比,我们可能会浪费大约两倍的时间和空间。
* 但唯一已知的案例源于糟糕的用户编程实践,这些实践已经非常缓慢,以至于这几乎没有什么区别。)
*
* 因为treenode的大小大约是常规节点的两倍,所以我们只在桶包含足够的节点以保证使用时才使用它们
* (参见TREEIFY_THRESHOLD)。当它们变得太小(由于移除或调整大小)时,它们被转换回普通的桶。
* 在用户hashCodes分布良好的用法中,很少使用树桶。
* 理想情况下,在随机hashCodes下,箱中节点的频率遵循
* 泊松分布(http://en.wikipedia.org/wiki/Poisson_distribution),
* 默认调整大小阈值为0.75,参数平均约为0.5,尽管由于调整大小粒度而存在很大差异。
* 忽略方差,列表大小k的预期出现次数为(exp(-0.5) * pow(0.5, k) / factorial(k))。第一个值是:
*
* 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
* more: less than 1 in ten million
*
* 树桶的根通常是它的第一个节点。然而,有时(目前仅在Iterator.remove上),
* 根可能在其他地方,但可以通过父链接(方法TreeNode.root())恢复。
*
* 所有适用的内部方法都接受哈希码作为参数(通常由公共方法提供),允许它们相互调用而无需重新计算用户哈希码。
* 大多数内部方法也接受“tab”参数,通常是当前表,但在调整大小或转换时可能是新表或旧表。
*
* 当bin列表被树化、拆分或非树化时,我们将它们保持相同的相对访问/遍历顺序(即字段Node.next),
* 以更好地保留局部性,并稍微简化调用iterator.remove的拆分和遍历处理。
* 当在插入时使用比较器时,为了在重新平衡中保持总排序(或尽可能接近),我们比较类和identityHashCodes作为决定因素。
*
* 由于子类LinkedHashMap的存在,普通模式与树模式之间的使用和转换变得复杂。
* 请参阅下面定义的在插入、删除和访问时调用的钩子方法,这些方法允许LinkedHashMap
* 内部保持独立于这些机制。(这还需要将映射实例传递给一些可能创建新节点的实用程序方法。)
*
* 类似于并发编程的基于ssa的编码风格有助于避免在所有扭曲指针操作中出现混叠错误。
*/

/**
* 默认初始容量-必须是2的幂。
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
* 如果隐式指定了更大的值,则使用最大容量。
* 由任意一个带参数的构造函数调用。必须是2的幂<= 1<<30。
*/
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
* 在构造函数中未指定时使用的负载因子(默认负载因子)。
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
* 使用树而不是列表的bin计数阈值。当向至少有这么多节点的桶中添加元素时,桶将转换为树。
* 该值必须大于2,并且应该至少为8,以符合在树木移除中关于收缩后转换回普通桶的假设。
* (当桶上的节点数大于等于该值会由链表转换成红黑树)
*/
static final int TREEIFY_THRESHOLD = 8;

/**
* 在调整大小操作期间取消树化(拆分)bin的bin计数阈值。
* 应小于TREEIFY_THRESHOLD,且最多为6,以便在移除时进行收缩检测。
*(当桶上的节点数小于等于该值会由红黑树转换成链表)
*/
static final int UNTREEIFY_THRESHOLD = 6;

/**
* 可以对桶进行树化的最小表容量。(否则,如果一个bin中的节点太多,则会调整表的大小。)
* 应该至少为4 * TREEIFY_THRESHOLD,以避免调整大小和树化阈值之间的冲突。
*(桶中结构转换为红黑树对应的table的最小容量)
*/
static final int MIN_TREEIFY_CAPACITY = 64;

/**
* 基本哈希bin节点,用于大多数条目。(参见下面的TreeNode子类,以及LinkedHashMap中的Entry子类。)
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; // 哈希值,存放元素到hashMap中时用来与其他元素的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;
}

public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }

public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}

public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}

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;
}
}

/* ---------------- Static utilities -------------- */

/**
* 计算key.hashCode()并将哈希的高位数扩展到低位数。
* 因为表使用了2的幂掩码,所以在当前掩码之上只变化几比特的哈希集总是会发生冲突。
* (其中一个已知的例子是在小表格中保存连续整数的Float键集。)
* 因此,我们应用一个变换,将高比特的影响向下扩散。比特传播的速度、效用和质量之间存在权衡。
* 由于许多常见的哈希集已经合理分布(因此不会从扩展中受益),并且由于我们使用树来处理箱中的大型碰撞集,
* 因此我们只是以最便宜的方式对一些移位的位进行异或,以减少系统损失,并合并最高位的影响,
* 否则由于表边界的原因,这些位在索引计算中永远不会使用。
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

/**
* 如果x的Class是" Class C implements Comparable<C>"的形式,则返回它的Class,否则返回null。
*/
static Class<?> comparableClassFor(Object x) {
if (x instanceof Comparable) {
Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
if ((c = x.getClass()) == String.class) // bypass checks
return c;
if ((ts = c.getGenericInterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
if (((t = ts[i]) instanceof ParameterizedType) &&
((p = (ParameterizedType)t).getRawType() ==
Comparable.class) &&
(as = p.getActualTypeArguments()) != null &&
as.length == 1 && as[0] == c) // type arg is c
return c;
}
}
}
return null;
}

/**
* 如果x匹配kc (k筛选的可比较类),则返回k. compareto (x),否则为0。
*/
@SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
static int compareComparables(Class<?> kc, Object k, Object x) {
return (x == null || x.getClass() != kc ? 0 :
((Comparable)k).compareTo(x));
}

/**
* 返回给定目标容量的2次幂大小。
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
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;
}

/* ---------------- Fields -------------- */

/**
* 表,在第一次使用时初始化,并根据需要调整大小。
* 在分配时,长度总是2的幂。(我们也允许某些操作的长度为零,以允许目前不需要的引导机制。)
* (存储元素的数组,总是2的幂次方)
*/
transient Node<K,V>[] table;

/**
* 保存缓存的entrySet()。注意,AbstractMap字段用于keySet()和values()。
* (存放具体元素的集)
*/
transient Set<Map.Entry<K,V>> entrySet;

/**
* 此映射中包含的键值映射的数量。
*(存放元素的个数,注意,这个不等于数组的长度)
*/
transient int size;

/**
* 结构修改是指改变HashMap中的映射数量或以其他方式修改其内部结构(例如,重新散列)。
* 该字段用于使HashMap的集合视图上的迭代器快速失败。(见ConcurrentModificationException)。
*(每次扩容和更改map结构的计数器)
*/
transient int modCount;

/**
* 要调整大小的下一个大小值(容量*负载因子)。
* (阈值,当实际大小超过阈值时,会进行扩容)
*/
// (序列化时javadoc描述为真。
// 另外,如果表数组没有被分配
// 字段保存初始数组容量,或者零表示
// DEFAULT_INITIAL_CAPACITY)。
int threshold;

/**
* 哈希表的负载因子。
*/
final float loadFactor;

/* ---------------- Public operations -------------- */

/**
* 构造具有指定初始容量和负载因子的空HashMap。
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
//指定的容量大小不可以小于0,否则将抛出IllegalArgumentException异常
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//判定指定的容量大小是否大于HashMap的容量极限
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
//指定的负载因子不可以小于0或为NaN,若判定成立则抛出IllegalArgumentException异常
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
// 初始容量暂时放到threshold,在resize中再赋值给newCap进行table初始化
// 设置“HashMap阈值”,当HashMap中存储数据的数量达到threshold时,就需要将HashMap的容量加倍。
//tableSizeFor用于查找到大于给定数值的最近2次幂值,比如给定18就是32。给定33就是64
this.threshold = tableSizeFor(initialCapacity);
}

/**
* 用指定的初始值构造一个空的HashMap容量和默认负载因子(0.75)。
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
* 使用默认初始容量(16)和默认负载因子(0.75)构造一个空的HashMap。
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

/**
* 构造一个与指定Map具有相同映射的新HashMap。
* HashMap是用默认负载因子(0.75)创建的,初始容量足以在指定的Map中保存映射。
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}

/**
* 实现了Map.putAll和Map的构造
*/
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
// 判断map是否已经初始化
if (table == null) { // pre-size
// 未初始化,s为m的实际元素个数
// ft = s/loadFactor => s = ft*loadFactor
// ft指的是要添加s个元素所需的最小容量
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
// table未初始化,threshold实际上存放的是初始化容量
// 如果添加s个元素所需的最小容量大于初始化容量,则将最小容量扩容为最接近2的幂次方大小作为初始化
// 注意,这里不是初始化阈值
threshold = tableSizeFor(t);
}
else if (s > threshold)
// 已经初始化,并且m元素个数大于阈值,进行扩容处理
resize();
// 将m中所有元素添加至HashMap中,如果table未初始化,putVal中会调用resize()初始化或者扩容
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);
}
}
}

/**
* 返回此映射中键值映射的个数
*/
public int size() {
return size;
}

/**
* 如果此映射不包含键值映射,则返回true
*/
public boolean isEmpty() {
return size == 0;
}

/**
* 返回指定键映射到的值,如果此映射不包含该键的映射,则返回null。
*
* 更正式地说,如果这个映射包含一个从键k到值v的映射,
* 使得(key==null ?K ==null: key.equals(K)),则此方法返回v;否则返回null。(最多只能有一个这样的映射。)
*
* 返回值为null并不一定表示映射不包含该键的映射;也有可能映射显式地将键映射为null。
* containsKey操作可以用来区分这两种情况。
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}

/**
* 实现了Map.get相关方法
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}

/**
* 如果此映射包含指定键的映射,则返回true
*/
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}

/**
* 将指定值与此映射中的指定键关联。如果映射以前包含键的映射,则替换旧值。
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

/**
* 实现了Map.put和相关方法
*/
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)
// table未初始化或者长度为0,则进行扩容
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
// (n - 1) & hash 确定元素存放在哪个桶中
// 桶为空,新生成节点放入桶中(此时,这个结点是放在数组中)
tab[i] = newNode(hash, key, value, null);
else {
// 桶中已经存在元素,处理hash冲突
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 快速判断第一个节点table[i]的key是否与插入的key一样
// 若相同则直接使用插入的p值替换掉旧的值e
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
// 如果节点数量达到阈值(默认为8),执行treeifyBin方法
// 根据HashMap数组来决定是否转换为红黑树
// 只有当数组长度大于或者等于64的情况下,才会执行红黑树操作,减少搜索次数
// 否则,只是对数组扩容
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
// 如果链表节点的key与插入元素的key相等,跳出循环
break;
// 用于遍历桶中的链表,与前面的 e = p.next组合,遍历链表
p = e;
}
}
if (e != null) { // existing mapping for key
// 在桶中找到key值、hash值与插入元素相等的节点
// 记录e的value
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
// onlyIfAbsent为false或者oldValue为null,用新值替换旧值
e.value = value;
// 访问后回调
afterNodeAccess(e);
// 返回旧值
return oldValue;
}
}
++modCount; // 结构性修改
if (++size > threshold)
// 如果实际大小大于阈值则扩容
resize();
afterNodeInsertion(evict); // 插入后回调
return null;
}

/**
* 初始化或加倍表大小。如果为空,则按照字段阈值中持有的初始容量目标进行分配。
* 否则,由于我们使用的是2的幂展开,因此每个桶中的元素必须保持在相同的索引上,或者在新表中以2的幂偏移量移动。
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length; // 原数组如果为空,则长度赋值为0
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
// 如果原数组长度大于0,说明HashMap已经初始化过了,是一次正常的扩容
if (oldCap >= MAXIMUM_CAPACITY) {
// 判断旧的容量是否大于容量最大值(2^30),如果是,则无法扩容,那么修改阈值为 Integer.MAX_VALUE
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// // 原数组长度大于等于初始化长度16,并且原数组长度扩大1倍也小于 2^30次方,扩容为原来的2倍
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // 初始容量被置于阈值
// 如果旧容量 = 0 且 旧阈值 > 0,说明是通过构造方法创建的HashMap
// 新容量直接等于旧阈值
// 创建对象时初始化容量大小放在threshold中,此时只需要将其作为新的数组容量
newCap = oldThr;
else { // 零初始阈值表示使用默认值
// 无参构造函数创建的对象在这里计算容量和阈值
newCap = DEFAULT_INITIAL_CAPACITY; // 数组长度初始化为16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 数组阈值初始化为12
}
if (newThr == 0) {
// 创建时指定了初始化容量或者负载因子,在这里进行阈值初始化
// 或者扩容前旧容量小于16,在这里计算新的resize上限
float ft = (float)newCap * loadFactor;
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];
table = newTab;
if (oldTab != null) {
// 把每个bucket都移动到新的buckets中
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
// 当前桶位数据不为空,但是不能判断是链表还是红黑树结构
oldTab[j] = null;
if (e.next == null)
// 如果e结点不存在下一个结点,说明e是单个元素,则直接放入新数组的对应位置
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 将红黑树拆分成两棵子树,如果子树节点小于等于UNTREEIFY_THRESHOLD(默认为 6),
// 则将子树转换为链表,否则保持子树的树结构
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
// 否则e为链表,则对链表进行遍历
// 低位链表:存放在扩容之后的数组的下标位置,与当前数组下标位置一致
// loHead:低位链表头节点
// loTail低位链表尾节点
Node<K,V> loHead = null, loTail = null;
// 高位链表,存放扩容之后的数组的下标位置,=原索引+扩容之前数组容量
// hiHead:高位链表头节点
// hiTail:高位链表尾节点
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
// 通过 & 运算计算当前结点的hash值是高位为1还是0
if ((e.hash & oldCap) == 0) {
// 高位为0,放入低位链表中
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
// 高位为1,放入高位链表中
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
// 原索引放到bucket里,将低位链表头结点指向原来的索引位置
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
// 原索引+oldCap放到bucket里,将高位链表头结点指向新的索引位置
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}

/**
* 替换节点中给定哈希索引处的所有链接节点,除非表太小,在这种情况下调整大小。
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}

/**
* 将指定映射中的所有映射复制到此映射。这些映射将替换此映射对指定映射中当前任何键的任何映射。
*/
public void putAll(Map<? extends K, ? extends V> m) {
putMapEntries(m, true);
}

/**
* 从此映射中删除指定键的映射(如果存在)。
*/
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}

/**
* 实现Map.remove和相关方法
*/
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;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
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;
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);
}
}
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)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}

/**
* 从该映射中删除所有映射。这个调用返回后,映射将为空
*/
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;
}
}

/**
* 如果此映射将一个或多个键映射到指定值,则返回true
*/
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}

/**
* 返回此映射中包含的键的Set视图。集合由映射支持,因此对映射的更改反映在集合中,反之亦然。
* 如果在对set进行迭代时修改map(通过迭代器自己的remove操作除外),则迭代的结果是未定义的。
* set支持移除元素,即通过Iterator从map中移除对应的映射。remove,Set.remove, removeAll, retainAll和clear操作。
* 它不支持add或addAll操作。
*/
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}

final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<K> iterator() { return new KeyIterator(); }
public final boolean contains(Object o) { return containsKey(o); }
public final boolean remove(Object key) {
return removeNode(hash(key), key, null, false, true) != null;
}
public final Spliterator<K> spliterator() {
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}

/**
* 返回此映射中包含的值的集合视图。集合由映射支持,因此对映射的更改将反映在集合中,反之亦然。
* 如果在对集合进行迭代时修改map(通过迭代器自己的remove操作除外),则迭代的结果是未定义的。
* 该集合支持移除元素,即通过Iterator从map中移除对应的映射。Iterator.remove,Collection.remove,removeAll, retainAll和clear操作。
* 它不支持add或addAll操作。
*/
public Collection<V> values() {
Collection<V> vs = values;
if (vs == null) {
vs = new Values();
values = vs;
}
return vs;
}

final class Values extends AbstractCollection<V> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<V> iterator() { return new ValueIterator(); }
public final boolean contains(Object o) { return containsValue(o); }
public final Spliterator<V> spliterator() {
return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super V> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}

/**
* 返回此映射中包含的映射的Set视图。集合由映射支持,因此对映射的更改反映在集合中,反之亦然。
* 如果在对set进行迭代时修改map(通过迭代器自己的remove操作或通过对迭代器返回的map项执行setValue操作除外),
* 则迭代的结果是未定义的。set支持移除元素,即通过Iterator从map中移除对应的映射。Iterator.remove, Set.remove, removeAll, retainAll和clear操作。
* 它不支持add或addAll操作。
*/
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}

final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
public final boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Node<K,V> candidate = getNode(hash(key), key);
return candidate != null && candidate.equals(e);
}
public final boolean remove(Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Object value = e.getValue();
return removeNode(hash(key), key, value, true, true) != null;
}
return false;
}
public final Spliterator<Map.Entry<K,V>> spliterator() {
return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}

// Overrides of JDK8 Map extension methods

@Override
public V getOrDefault(Object key, V defaultValue) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}

@Override
public V putIfAbsent(K key, V value) {
return putVal(hash(key), key, value, true, true);
}

@Override
public boolean remove(Object key, Object value) {
return removeNode(hash(key), key, value, true, true) != null;
}

@Override
public boolean replace(K key, V oldValue, V newValue) {
Node<K,V> e; V v;
if ((e = getNode(hash(key), key)) != null &&
((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
e.value = newValue;
afterNodeAccess(e);
return true;
}
return false;
}

@Override
public V replace(K key, V value) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) != null) {
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null;
}

@Override
public V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) {
if (mappingFunction == null)
throw new NullPointerException();
int hash = hash(key);
Node<K,V>[] tab; Node<K,V> first; int n, i;
int binCount = 0;
TreeNode<K,V> t = null;
Node<K,V> old = null;
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
if ((first = tab[i = (n - 1) & hash]) != null) {
if (first instanceof TreeNode)
old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
else {
Node<K,V> e = first; K k;
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
V oldValue;
if (old != null && (oldValue = old.value) != null) {
afterNodeAccess(old);
return oldValue;
}
}
V v = mappingFunction.apply(key);
if (v == null) {
return null;
} else if (old != null) {
old.value = v;
afterNodeAccess(old);
return v;
}
else if (t != null)
t.putTreeVal(this, tab, hash, key, v);
else {
tab[i] = newNode(hash, key, v, first);
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
}
++modCount;
++size;
afterNodeInsertion(true);
return v;
}

public V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if (remappingFunction == null)
throw new NullPointerException();
Node<K,V> e; V oldValue;
int hash = hash(key);
if ((e = getNode(hash, key)) != null &&
(oldValue = e.value) != null) {
V v = remappingFunction.apply(key, oldValue);
if (v != null) {
e.value = v;
afterNodeAccess(e);
return v;
}
else
removeNode(hash, key, null, false, true);
}
return null;
}

@Override
public V compute(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if (remappingFunction == null)
throw new NullPointerException();
int hash = hash(key);
Node<K,V>[] tab; Node<K,V> first; int n, i;
int binCount = 0;
TreeNode<K,V> t = null;
Node<K,V> old = null;
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
if ((first = tab[i = (n - 1) & hash]) != null) {
if (first instanceof TreeNode)
old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
else {
Node<K,V> e = first; K k;
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
}
V oldValue = (old == null) ? null : old.value;
V v = remappingFunction.apply(key, oldValue);
if (old != null) {
if (v != null) {
old.value = v;
afterNodeAccess(old);
}
else
removeNode(hash, key, null, false, true);
}
else if (v != null) {
if (t != null)
t.putTreeVal(this, tab, hash, key, v);
else {
tab[i] = newNode(hash, key, v, first);
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
}
++modCount;
++size;
afterNodeInsertion(true);
}
return v;
}

@Override
public V merge(K key, V value,
BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
if (value == null)
throw new NullPointerException();
if (remappingFunction == null)
throw new NullPointerException();
int hash = hash(key);
Node<K,V>[] tab; Node<K,V> first; int n, i;
int binCount = 0;
TreeNode<K,V> t = null;
Node<K,V> old = null;
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
if ((first = tab[i = (n - 1) & hash]) != null) {
if (first instanceof TreeNode)
old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
else {
Node<K,V> e = first; K k;
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
}
if (old != null) {
V v;
if (old.value != null)
v = remappingFunction.apply(old.value, value);
else
v = value;
if (v != null) {
old.value = v;
afterNodeAccess(old);
}
else
removeNode(hash, key, null, false, true);
return v;
}
if (value != null) {
if (t != null)
t.putTreeVal(this, tab, hash, key, value);
else {
tab[i] = newNode(hash, key, value, first);
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
}
++modCount;
++size;
afterNodeInsertion(true);
}
return value;
}

@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key, e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}

@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
Node<K,V>[] tab;
if (function == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
e.value = function.apply(e.key, e.value);
}
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}

/* ------------------------------------------------------------ */
// Cloning and serialization

/**
* Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and
* values themselves are not cloned.
*
* @return a shallow copy of this map
*/
@SuppressWarnings("unchecked")
@Override
public Object clone() {
HashMap<K,V> result;
try {
result = (HashMap<K,V>)super.clone();
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
result.reinitialize();
result.putMapEntries(this, false);
return result;
}

// These methods are also used when serializing HashSets
final float loadFactor() { return loadFactor; }
final int capacity() {
return (table != null) ? table.length :
(threshold > 0) ? threshold :
DEFAULT_INITIAL_CAPACITY;
}

/**
* Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
* serialize it).
*
* @serialData The <i>capacity</i> of the HashMap (the length of the
* bucket array) is emitted (int), followed by the
* <i>size</i> (an int, the number of key-value
* mappings), followed by the key (Object) and value (Object)
* for each key-value mapping. The key-value mappings are
* emitted in no particular order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws IOException {
int buckets = capacity();
// Write out the threshold, loadfactor, and any hidden stuff
s.defaultWriteObject();
s.writeInt(buckets);
s.writeInt(size);
internalWriteEntries(s);
}

/**
* Reconstitutes this map from a stream (that is, deserializes it).
* @param s the stream
* @throws ClassNotFoundException if the class of a serialized object
* could not be found
* @throws IOException if an I/O error occurs
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {

ObjectInputStream.GetField fields = s.readFields();

// Read loadFactor (ignore threshold)
float lf = fields.get("loadFactor", 0.75f);
if (lf <= 0 || Float.isNaN(lf))
throw new InvalidObjectException("Illegal load factor: " + lf);

lf = Math.min(Math.max(0.25f, lf), 4.0f);
HashMap.UnsafeHolder.putLoadFactor(this, lf);

reinitialize();

s.readInt(); // Read and ignore number of buckets
int mappings = s.readInt(); // Read number of mappings (size)
if (mappings < 0) {
throw new InvalidObjectException("Illegal mappings count: " + mappings);
} else if (mappings == 0) {
// use defaults
} else if (mappings > 0) {
float fc = (float)mappings / lf + 1.0f;
int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ?
DEFAULT_INITIAL_CAPACITY :
(fc >= MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY :
tableSizeFor((int)fc));
float ft = (float)cap * lf;
threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?
(int)ft : Integer.MAX_VALUE);

// Check Map.Entry[].class since it's the nearest public type to
// what we're actually creating.
SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, cap);
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] tab = (Node<K,V>[])new Node[cap];
table = tab;

// Read the keys and values, and put the mappings in the HashMap
for (int i = 0; i < mappings; i++) {
@SuppressWarnings("unchecked")
K key = (K) s.readObject();
@SuppressWarnings("unchecked")
V value = (V) s.readObject();
putVal(hash(key), key, value, false, false);
}
}
}

// Support for resetting final field during deserializing
private static final class UnsafeHolder {
private UnsafeHolder() { throw new InternalError(); }
private static final sun.misc.Unsafe unsafe
= sun.misc.Unsafe.getUnsafe();
private static final long LF_OFFSET;
static {
try {
LF_OFFSET = unsafe.objectFieldOffset(HashMap.class.getDeclaredField("loadFactor"));
} catch (NoSuchFieldException e) {
throw new InternalError();
}
}
static void putLoadFactor(HashMap<?, ?> map, float lf) {
unsafe.putFloat(map, LF_OFFSET, lf);
}
}

/* ------------------------------------------------------------ */
// iterators

abstract class HashIterator {
Node<K,V> next; // next entry to return
Node<K,V> current; // current entry
int expectedModCount; // for fast-fail
int index; // current slot

HashIterator() {
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) { // advance to first entry
do {} while (index < t.length && (next = t[index++]) == null);
}
}

public final boolean hasNext() {
return next != null;
}

final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}

public final void remove() {
Node<K,V> p = current;
if (p == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
K key = p.key;
removeNode(hash(key), key, null, false, false);
expectedModCount = modCount;
}
}

final class KeyIterator extends HashIterator
implements Iterator<K> {
public final K next() { return nextNode().key; }
}

final class ValueIterator extends HashIterator
implements Iterator<V> {
public final V next() { return nextNode().value; }
}

final class EntryIterator extends HashIterator
implements Iterator<Map.Entry<K,V>> {
public final Map.Entry<K,V> next() { return nextNode(); }
}

/* ------------------------------------------------------------ */
// spliterators

static class HashMapSpliterator<K,V> {
final HashMap<K,V> map;
Node<K,V> current; // current node
int index; // current index, modified on advance/split
int fence; // one past last index
int est; // size estimate
int expectedModCount; // for comodification checks

HashMapSpliterator(HashMap<K,V> m, int origin,
int fence, int est,
int expectedModCount) {
this.map = m;
this.index = origin;
this.fence = fence;
this.est = est;
this.expectedModCount = expectedModCount;
}

final int getFence() { // initialize fence and size on first use
int hi;
if ((hi = fence) < 0) {
HashMap<K,V> m = map;
est = m.size;
expectedModCount = m.modCount;
Node<K,V>[] tab = m.table;
hi = fence = (tab == null) ? 0 : tab.length;
}
return hi;
}

public final long estimateSize() {
getFence(); // force init
return (long) est;
}
}

static final class KeySpliterator<K,V>
extends HashMapSpliterator<K,V>
implements Spliterator<K> {
KeySpliterator(HashMap<K,V> m, int origin, int fence, int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}

public KeySpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid || current != null) ? null :
new KeySpliterator<>(map, lo, index = mid, est >>>= 1,
expectedModCount);
}

public void forEachRemaining(Consumer<? super K> action) {
int i, hi, mc;
if (action == null)
throw new NullPointerException();
HashMap<K,V> m = map;
Node<K,V>[] tab = m.table;
if ((hi = fence) < 0) {
mc = expectedModCount = m.modCount;
hi = fence = (tab == null) ? 0 : tab.length;
}
else
mc = expectedModCount;
if (tab != null && tab.length >= hi &&
(i = index) >= 0 && (i < (index = hi) || current != null)) {
Node<K,V> p = current;
current = null;
do {
if (p == null)
p = tab[i++];
else {
action.accept(p.key);
p = p.next;
}
} while (p != null || i < hi);
if (m.modCount != mc)
throw new ConcurrentModificationException();
}
}

public boolean tryAdvance(Consumer<? super K> action) {
int hi;
if (action == null)
throw new NullPointerException();
Node<K,V>[] tab = map.table;
if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
while (current != null || index < hi) {
if (current == null)
current = tab[index++];
else {
K k = current.key;
current = current.next;
action.accept(k);
if (map.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
}
}
return false;
}

public int characteristics() {
return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
Spliterator.DISTINCT;
}
}

static final class ValueSpliterator<K,V>
extends HashMapSpliterator<K,V>
implements Spliterator<V> {
ValueSpliterator(HashMap<K,V> m, int origin, int fence, int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}

public ValueSpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid || current != null) ? null :
new ValueSpliterator<>(map, lo, index = mid, est >>>= 1,
expectedModCount);
}

public void forEachRemaining(Consumer<? super V> action) {
int i, hi, mc;
if (action == null)
throw new NullPointerException();
HashMap<K,V> m = map;
Node<K,V>[] tab = m.table;
if ((hi = fence) < 0) {
mc = expectedModCount = m.modCount;
hi = fence = (tab == null) ? 0 : tab.length;
}
else
mc = expectedModCount;
if (tab != null && tab.length >= hi &&
(i = index) >= 0 && (i < (index = hi) || current != null)) {
Node<K,V> p = current;
current = null;
do {
if (p == null)
p = tab[i++];
else {
action.accept(p.value);
p = p.next;
}
} while (p != null || i < hi);
if (m.modCount != mc)
throw new ConcurrentModificationException();
}
}

public boolean tryAdvance(Consumer<? super V> action) {
int hi;
if (action == null)
throw new NullPointerException();
Node<K,V>[] tab = map.table;
if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
while (current != null || index < hi) {
if (current == null)
current = tab[index++];
else {
V v = current.value;
current = current.next;
action.accept(v);
if (map.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
}
}
return false;
}

public int characteristics() {
return (fence < 0 || est == map.size ? Spliterator.SIZED : 0);
}
}

static final class EntrySpliterator<K,V>
extends HashMapSpliterator<K,V>
implements Spliterator<Map.Entry<K,V>> {
EntrySpliterator(HashMap<K,V> m, int origin, int fence, int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}

public EntrySpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid || current != null) ? null :
new EntrySpliterator<>(map, lo, index = mid, est >>>= 1,
expectedModCount);
}

public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
int i, hi, mc;
if (action == null)
throw new NullPointerException();
HashMap<K,V> m = map;
Node<K,V>[] tab = m.table;
if ((hi = fence) < 0) {
mc = expectedModCount = m.modCount;
hi = fence = (tab == null) ? 0 : tab.length;
}
else
mc = expectedModCount;
if (tab != null && tab.length >= hi &&
(i = index) >= 0 && (i < (index = hi) || current != null)) {
Node<K,V> p = current;
current = null;
do {
if (p == null)
p = tab[i++];
else {
action.accept(p);
p = p.next;
}
} while (p != null || i < hi);
if (m.modCount != mc)
throw new ConcurrentModificationException();
}
}

public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
int hi;
if (action == null)
throw new NullPointerException();
Node<K,V>[] tab = map.table;
if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
while (current != null || index < hi) {
if (current == null)
current = tab[index++];
else {
Node<K,V> e = current;
current = current.next;
action.accept(e);
if (map.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
}
}
return false;
}

public int characteristics() {
return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
Spliterator.DISTINCT;
}
}

/* ------------------------------------------------------------ */
// LinkedHashMap support


/*
* The following package-protected methods are designed to be
* overridden by LinkedHashMap, but not by any other subclass.
* Nearly all other internal methods are also package-protected
* but are declared final, so can be used by LinkedHashMap, view
* classes, and HashSet.
*/

// Create a regular (non-tree) node
Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
return new Node<>(hash, key, value, next);
}

// For conversion from TreeNodes to plain nodes
Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
return new Node<>(p.hash, p.key, p.value, next);
}

// Create a tree bin node
TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
return new TreeNode<>(hash, key, value, next);
}

// For treeifyBin
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}

/**
* Reset to initial default state. Called by clone and readObject.
*/
void reinitialize() {
table = null;
entrySet = null;
keySet = null;
values = null;
modCount = 0;
threshold = 0;
size = 0;
}

// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }

// Called only from writeObject, to ensure compatible ordering.
void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
Node<K,V>[] tab;
if (size > 0 && (tab = table) != null) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
s.writeObject(e.key);
s.writeObject(e.value);
}
}
}
}

/* ------------------------------------------------------------ */
// Tree bins

/**
* Tree节点结构。LinkedHashMap延伸。结构(又扩展Node),因此可以用作常规节点或链接节点的扩展。
*/
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; // 需要在删除后解除链接
boolean red; // 判断颜色的标识
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}

/**
* 返回包含此节点的树的根。
*/
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}

/**
* 确保给定的根是其桶的第一个节点。
*/
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);
}
}

/**
* 用给定的散列和键查找从根p开始的节点。
* kc参数在第一次使用比较键时缓存comparableClassFor(key)。
*/
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;
}

/**
* 对根节点调用find
*/
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}

/**
* 当hashCodes相等且不可比较时,用于排序插入的Tie-breaking实用程序。
* 我们不需要一个总顺序,只需要一个一致的插入规则来保持跨再平衡的等价性。不必要的断线进一步简化了测试。
*/
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;
}

/**
* 形成从该节点链接的节点的树
*/
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);
}

/**
* 返回非treenode的列表,替换从该节点链接的那些节点
*/
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;
}

/**
* 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;
}
}
}

/**
* 删除在此调用之前必须存在的给定节点。
* 这比典型的红黑删除代码更混乱,因为我们不能将内部节点的内容与由在遍历期间可独立访问的“next”指针固定的叶继承节点交换。
* 所以我们交换树形连杆。如果当前树的节点太少,则将该二进制文件转换回普通二进制文件。
* (测试触发2到6个节点,这取决于树的结构)。
*/
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);
}

/**
* 将树仓中的节点拆分为上树仓和下树仓,如果太小则拆分为非树仓。
* 只能从resize中调用;参见上面关于分割位和索引的讨论。
*/
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);
}
}
}

/* ------------------------------------------------------------ */
// 红黑树方法,全部改编自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;
}
}
}
}
}

/**
* 递归不变检验
*/
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;
}
}
}