public class HashMap3. Mapextends AbstractMap implements Map , Cloneable, Serializable { }
以上图片仅为了演示结构和原理,对容量等细节没有考虑和说明
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
2. 属性及描述:
- 默认初始化容量:是在使用无初始化容量构造时,创建的初始数组容量大小,此种构造在新建时并不会创建数组,而是在进行首次存放元素时才会进行数组初始化
- 最大容量: 标准扩容(即常规的扩容方式,每次扩容是上一次容量的两倍)的最大容量,如果容量大于了这个值,则将容量扩容至 Integer.MAX_VALUE
- 默认加载因子: 在使用无加载因子构造时使用的默认的加载因子
- 树化临界值: 当某个桶中的链表节点数大于此值时,则转化为树
- 链表化临界值: 当某个桶中的链表节点数小于此值时,则转为链表
- 最小树化容量: 只有当当前散列表中的容量大于等的此值时,才允许将符合要求的链表转为树,否则就只进行扩容操作
// 表(节点数组)
transient Node[] table;
// 节点集合
transient Set> entrySet;
// 大小:map中键值对的数量
transient int size;
// 结构上的修改次数 (添加或者删除, 查询或者修改值不会造成结构变化)
transient int modCount;
// 临界值
int threshold;
// 加载因子
final float loadFactor;
// 键集合
transient Set keySet;
// 值集合
transient Collection values;
3. 节点
- 表: table就是一个 Node
数组,数组的长度就是散列表的容量,每一个数组元素就表示一个桶 - 节点集合: 存放所有节点的集合
- 大小: 当前散列表中目前元素个数
- 修改次数: 记录进行结构化修改的次数,用于判断同步,比较期望值和操作后的值是否一致,来判断是否同步
- 临界值: 用于判断是否需要扩容的临界值,当前值为当前容量乘以加载因子
- 加载因子: 用于计算散列表每次扩容的临界值
- 键集合和值集合:定义在 AbstractMap 中相关实现也是
- 链节点
链表节点描述:用于存放每个键值对的键和值以及对应的哈希值和下一个节点
注意:
1.由下面的节点代码可以看出, JAVA中的散列表的元素为链表时是单向链表,因为只有指向下一个节点的next属性
2.节点的构造只有一个全参构造,所以在HashMap中才会出现next为null时仍要写的情况
static class Nodeimplements Map.Entry { // hash值 final int hash; // 键 final K key; // 值 V value; // 下一个节点 Node next; // 节点全参构造 Node(int hash, K key, V value, Node 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; } // 获取hash值 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; } }
- 树节点
篇幅太长,移至文章结尾
四. 一些重要的方法 1.hash树节点描述:树节点有两个结构:
一是双向链表,树节点的定义中既有指向上一节点的引用变量也有指向下一节点的引用变量(下一节点的变量定义是继承过来的);
二是树结构(红黑树),既有父级节点引用变量,也有左右子节点的引用变量,还有变量指明该节点是否是红节点.
树这一节点中有很多内容,本人就在此挖个坑,等本人把树吃透后来填
static final int hash(Object key) {
int h;
// 如果 h 小于2^(16-1)次幂,得到值仍为 h
// 如果 h 大于2^16(16-1),得到的值为 h hash后的值,此值小于 2^16
// 为什么时 2^16 ? 因为HashMap的容量是 int 类型,正数的最大值为 2^16 - 1
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
2.tableSizeFor描述:
此方法是JAVA的HashMap中获取哈希值的方法,此处不纠结hash算法的值是怎样计算的,不同语言有不同的hash实现;
将此方法放在此处是想说明为什么HashMap中的key可以有null,因为key为null时,返回的hash值直接是 0 .
// 结果是返回一个不小于给定值的最小2的整次幂数,用作表大小
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1; // n = n | n >>> 1 从n的有效最高位(除了符号位以外的第一个 1 )开始的 2 位都为 1 (如果位数大于等于 2)
n |= n >>> 2; // n = n | n >>> 2 基于上一步,结果是从n的有效最高位(除了符号位以外的第一个 1 )开始的 4 位都为 1 (如果位数大于等于 4)
n |= n >>> 4; // n = n | n >>> 4 基于上一步,结果是从n的有效最高位(除了符号位以外的第一个 1 )开始的 8 位都为 1 (如果位数大于等于 8)
n |= n >>> 8; // n = n | n >>> 8 基于上一步,结果是从n的有效最高位(除了符号位以外的第一个 1 )开始的 16 位都为 1 (如果位数大于等于 16)
n |= n >>> 16; // n = n | n >>> 16 基于上一步,结果是从n的有效最高位(除了符号位以外的第一个 1 )开始的所有位都为 1
// 以上算法会从 cap - 1 的有效最高位开始,后续位全部为 1
// 如果小于0,就为1 ,否则如果大于等于最大容量,就为最大容量,否则就为不小于给定值的最小2的整次幂数
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
描述:
上述方法中添加了注释, 对 n 的操作是无符号右移和按位或运算;
结果是返回了一个大于给定值同时又是 2 的整次幂的最小值
右移和或运算流程举例如下:
3.构造方法注意:
1.是符合要求的任意一个数,哪怕 n 是 2 的整次幂(二进制数只有一个 1 )
2.由上述操作的到的数字加 1 之后,得到一个 2 的整次幂数, 这个数必然会大于给定的数,因为任意一个给定数,将其从最高有效位开始至结束位的所有位都置为 1 得到的数必然会大于等于该数,加 1 之后必然大于该数
3.为什么 n 要等于 给定值 cap 减 1 :影响该算法的结果的关键在于最高有效位位置:如果 cap 不是 2 的整次幂,则值是否减 1 是没有影响的;如果 cap 是 2 的整次幂,如果不减 1 ,最高有效位就是cap 的最高有效位,方法的返回值就是 cap 的两倍,如果减 1 ,最高有效位就是 cap 的最高有效位的下一位,方法的返回值就是 cap 值;
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
// 不小于目标容量的最小 2 的整次幂
this.threshold = tableSizeFor(initialCapacity);
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(Map extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
4.resize描述:
1. 非集合构造方法中并没有创建散列表(节点数组)的操作,只是进行了加载因子和临界值的赋值;
2. 散列表的创建是在首次赋值时进行创建的
// 扩容算法,调用即扩容,不进行判断当前大小和容量以及临界值 final Node[] resize() { // 旧表 Node [] oldTab = table; // 旧表容量 int oldCap = (oldTab == null) ? 0 : oldTab.length; // 旧表临界值 int oldThr = threshold; // 定义初始化信标容量和临界值 int newCap, newThr = 0; // 旧容量大于 0 如果不是新new的哈希表的首次添加元素,则一定会执行此分支, // 结果是,每次扩容结果为之前容量的两倍或者是最大 if (oldCap > 0) { // 旧表容量大于最大容量,临界值定义为最大整数,旧表已经是最大容量表 // 不能再扩容,返回原表即可 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } // 否则新的容量为旧容量左移一位(旧容量的两倍) // 并且小于最大容量且旧容量大于等于默认初始化值 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) // 新临界值为旧临界值左移一位(旧临界值的两倍) newThr = oldThr << 1; // double threshold } // 旧容量不大于 0 且旧临界值大于 0 // TODO 什么情况下执行此分支? else if (oldThr > 0) // initial capacity was placed in threshold 初始化容量放置在临界值中 // 新容量为旧的临界值 newCap = oldThr; // 旧容量不大于 0 且旧临界值不大于 0 ,新new的哈希表首次添加元素是执行 else { // zero initial threshold signifies using defaults 从零开始初始化使用默认值 newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } // 新临界值为 0 ,即旧容量不大于 0 且旧临界值大于 0 的情况 // TODO 什么情况下会执行该分支 if (newThr == 0) { // 计算新临界值 float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; @SuppressWarnings({"rawtypes","unchecked"}) Node [] newTab = (Node [])new Node[newCap]; table = newTab; // 扩容后重新计算元素位置,由于每次扩容的结果是原容量的两倍,所以结果就是原容量的二进制数左移一位 // 计算元素在表中的位置时是用 e.hash & (table.length -1),获得一个小于表长度的数字作为元素在表中的数组下标 // 如:0000 1011 & 0010 0000 - 1 = 0000 1011 & 0001 1111 = 0000 1011 // 基于以上两条,计算元素在数组中的下标有没有发生变化关键是 e.hash 对应原容量的有效位的位置的值是否为 1 // 原因是计算时新容量比原容量多了一位计算位,产生异常就在该计算位的不同 // 结果是要么不变,要么加上 oldCap // e.hash 对应原容量的有效位的位置为 0 --------> 结果不变 // 如: e.hash: 0000 1011 // oldCap: 0010 0000 // 0000 1011 & 0010 0000 - 1 = 0000 1011 & 0001 1111 = 0000 1011 // 0000 1011 & 0100 0000 - 1 = 0000 1011 & 0011 1111 = 0000 1011 // e.hash 对应原容量的有效位的位置为 1 ---> 结果为原值加旧容量(即二进制数中多了旧容量有效位对应的 1 ) // 如: e.hash: 0010 1011 // oldCap: 0010 0000 // 0010 1011 & 0010 0000 - 1 = 0010 1011 & 0001 1111 = 0000 1011 // 0010 1011 & 0100 0000 - 1 = 0010 1011 & 0011 1111 = 0010 1011 if (oldTab != null) { // 遍历数组中所有的链表 for (int j = 0; j < oldCap; ++j) { Node e; // 该桶上由节点 if ((e = oldTab[j]) != null) { // 元素置空的原因? oldTab[j] = null; //该桶只有一个节点 if (e.next == null) // 重新hash,并将元素放到桶中 newTab[e.hash & (newCap - 1)] = e; // 如果由多个节点,先判断有没有转化为树 else if (e instanceof TreeNode) ((TreeNode )e).split(this, newTab, j, oldCap); // 链 else { // preserve order // 在表中位置不发生变化的元素头节点和当前节点 Node loHead = null, loTail = null; // 在表中位置发生了变化的元素头节点和当前节点 Node hiHead = null, hiTail = null; // 下一个节点 Node next; // 遍历链表中所有的元素 do { next = e.next; // 由于容量值除了最高位为 1 以外,其他位全为 0 // 所以,如果 & 运算结果位 0 ,那么 oldCap 的最高位对应的 e.hash 的该位为 0 if ((e.hash & oldCap) == 0) { if (loTail == null) loHead = e; else loTail.next = 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; }
5.putVal描述:
1.结果是返回了扩容后的新散列表
2.e.hash & (cap - 1) 这个运算: 前文中提及,每一个节点中都会保存该节点key对应的hash值, 使用容量减一(cap - 1)作为掩码,可以使任意的值计算得到一个小于 cap 的值,这个值在 0 到 (cap - 1)之间,也刚好契合数组下标
3.原因: cap 是一个 2 的整次幂数, 减一之后得到的数 n 是最高有效位之前全为 0 ,从最高有效位开始全为 1 ,进行 & 运算(有 0 则 0)后得到的结果 m ,最高有效位之前全部为 0 ,所以 m 不可能大于 n,必然小于 n + 1
4.为什么建议在大致知道要添加到散列表中数量时,传入容量值: resize过程中会对散列表中的元素重新哈希寻找位置,不断的resize很耗费性能,使用容量构造可以减少或者避免重新哈希
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node[] tab; Node p; int n, i;
// 如果没有表,初始化容量(默认值)
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 节点对应数组下标位置元素为 null ,即不存在该元素
if ((p = tab[i = (n - 1) & hash]) == null)
// 新建一个节点
tab[i] = newNode(hash, key, value, null);
else {
// 存放 key 相同的旧节点,不为 null 表示存在旧节点,为 null 表示不存在
Node e; K k;
// 如果hash值相同并且key也相同
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 将该节点赋给 e
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode)p).putTreeval(this, tab, hash, key, value);
// 不相同,遍历链表
else {
for (int binCount = 0; ; ++binCount) {
// 如果链表中某一节点的 next 为 null 不存在值为该 key 的节点,就新建一个节点,跳出循环
if ((e = p.next) == null) {
// 新建一个节点
p.next = newNode(hash, key, value, null);
// 如果达到了树化临界值,就进行树化
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 如果节点的hash值相同并且key也相同,存在值未该 key 的节点,就跳出循环
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
// 否则指针后移
p = e;
}
}
// 存在值为该 key 的节点,返回原来的值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// 如果是新添加节点,则修改次数和大小自增,如果大小大于临界值,就重新计算容量
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
6.putMapEntries描述:
1. 添加元素的主要方法,会先判断是否已经有了散列表,如果没有会先创建散列表;
2. 如果目标key已经存在相应的节点,就将原值替换并返回
final void putMapEntries(Map extends K, ? extends V> m, boolean evict) {
// 获取大小
int s = m.size();
if (s > 0) {
// 如果还没有table
if (table == null) { // pre-size
// 大小除以加载因子加 1 ,加 1 是为了消除小数的影响
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();
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);
}
}
}
7.removeNode描述: 是添加节点的主要方法,主要用于集合构造和putAll,clone方法中也用到了
final NoderemoveNode(int hash, Object key, Object value, boolean matchValue, boolean movable) { Node [] tab; Node p; int n, index; if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) { Node 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 )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 )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; }
8.getNode描述:移除一个节点,先找桶判断有没有节点,节点数量是否大于 1 ,返回删除的节点
final NodegetNode(int hash, Object key) { Node [] tab; Node first, e; int n; K k; // 数组存在并且 key 对应的桶位置不为 null 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 )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; }
9.treeifyBin描述:查找节点,返回定位节点
final void treeifyBin(Node[] tab, int hash) { int n, index; Node e; // 未达到最小树化容量(64)就只进行扩容 if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); // 表中在该桶中有节点(不判断数量,默认该桶中的节点数大于等于8) else if ((e = tab[index = (n - 1) & hash]) != null) { // 头和尾 TreeNode hd = null, tl = null; // 遍历链表,结果是的到一个双向链表 do { TreeNode 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); } }
五.常用方法 1.put描述:将桶进行树化的方法,从中可以找到判断当前散列表容量是否大于最小树化容量,如果小于就只进行扩容
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
2.putAll
public void putAll(Map extends K, ? extends V> m) {
putMapEntries(m, true);
}
3.get上面两个方法都是存放元素,直接调用存放元素值或者节点的方法
public V get(Object key) {
Node e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
4.containsKey
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
5.replace
public V replace(K key, V value) {
Node e;
if ((e = getNode(hash(key), key)) != null) {
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null;
}
6.remove上面三个方法是直接调用查找节点的方法,然后进行后续操作
public boolean remove(Object key, Object value) {
return removeNode(hash(key), key, value, true, true) != null;
}
7.containsValue移除方法是直接调用移除节点的方法
public boolean containsValue(Object value) {
Node[] tab; V v;
if ((tab = table) != null && size > 0) {
for (int i = 0; i < tab.length; ++i) {
for (Node e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}
8.clear
public void clear() {
Node[] tab;
// 修改次数自增
modCount++;
if ((tab = table) != null && size > 0) {
// 遍历清空表
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}
9.forEach
public void forEach(BiConsumer super K, ? super V> action) {
Node[] 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 e = tab[i]; e != null; e = e.next)
action.accept(e.key, e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
10.keySet上面三个方法是直接遍历整个集合,注意与containsKey的实现区别,key可以通过哈希值直接获取
public Set11.valueskeySet() { Set ks = keySet; if (ks == null) { ks = new KeySet(); keySet = ks; } return ks; }
public Collection12.entrySetvalues() { Collection vs = values; if (vs == null) { vs = new Values(); values = vs; } return vs; }
public Set13.isEmpty> entrySet() { Set > es; return (es = entrySet) == null ? (entrySet = new EntrySet()) : es; }
public boolean isEmpty() {
return size == 0;
}
14.size
public boolean isEmpty() {
return size == 0;
}
树节点代码:以上五个方法是直接对散列表属性进行操作
static final class TreeNodeextends linkedHashMap.Entry { TreeNode parent; // red-black tree links TreeNode left; TreeNode right; TreeNode prev; // needed to unlink next upon deletion boolean red; TreeNode(int hash, K key, V val, Node next) { super(hash, key, val, next); } final TreeNode root() { for (TreeNode r = this, p;;) { if ((p = r.parent) == null) return r; r = p; } } static void moveRootToFront(Node [] tab, TreeNode root) { int n; if (root != null && tab != null && (n = tab.length) > 0) { int index = (n - 1) & root.hash; TreeNode first = (TreeNode )tab[index]; if (root != first) { Node rn; tab[index] = root; TreeNode rp = root.prev; if ((rn = root.next) != null) ((TreeNode )rn).prev = rp; if (rp != null) rp.next = rn; if (first != null) first.prev = root; root.next = first; root.prev = null; } assert checkInvariants(root); } } final TreeNode find(int h, Object k, Class> kc) { TreeNode p = this; do { int ph, dir; K pk; TreeNode 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; } final TreeNode getTreeNode(int h, Object k) { return ((parent != null) ? root() : this).find(h, k, null); } 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 [] tab) { TreeNode root = null; // 遍历双向链表 for (TreeNode x = this, next; x != null; x = next) { next = (TreeNode )x.next; x.left = x.right = null; // 首次赋值根节点 if (root == null) { x.parent = null; x.red = false; root = x; } else { // 当前节点key K k = x.key; // 当前节点hash int h = x.hash; Class> kc = null; for (TreeNode p = root;;) { int dir, ph; K pk = p.key; // 当前节点hash小,左节点 if ((ph = p.hash) > h) dir = -1; // 当前节点hash大,右节点 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 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); } final Node untreeify(HashMap map) { Node hd = null, tl = null; for (Node q = this; q != null; q = q.next) { Node p = map.replacementNode(q, null); if (tl == null) hd = p; else tl.next = p; tl = p; } return hd; } final TreeNode putTreeval(HashMap map, Node [] tab, int h, K k, V v) { Class> kc = null; boolean searched = false; TreeNode root = (parent != null) ? root() : this; for (TreeNode 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 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 xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { Node xpn = xp.next; TreeNode 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 )xpn).prev = x; moveRootToFront(tab, balanceInsertion(root, x)); return null; } } } final void removeTreeNode(HashMap map, Node [] tab, boolean movable) { int n; if (tab == null || (n = tab.length) == 0) return; int index = (n - 1) & hash; TreeNode first = (TreeNode )tab[index], root = first, rl; TreeNode succ = (TreeNode )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 p = this, pl = left, pr = right, replacement; if (pl != null && pr != null) { TreeNode 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 sr = s.right; TreeNode pp = p.parent; if (s == pr) { // p was s's direct parent p.parent = s; s.right = p; } else { TreeNode 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 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 r = p.red ? root : balanceDeletion(root, replacement); if (replacement == p) { // detach TreeNode 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); } final void split(HashMap map, Node [] tab, int index, int bit) { TreeNode b = this; // Relink into lo and hi lists, preserving order TreeNode loHead = null, loTail = null; TreeNode hiHead = null, hiTail = null; int lc = 0, hc = 0; for (TreeNode e = b, next; e != null; e = next) { next = (TreeNode )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 TreeNode rotateLeft(TreeNode root, TreeNode p) { TreeNode 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 TreeNode rotateRight(TreeNode root, TreeNode p) { TreeNode 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 TreeNode balanceInsertion(TreeNode root, TreeNode x) { x.red = true; for (TreeNode 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 TreeNode balanceDeletion(TreeNode root, TreeNode x) { for (TreeNode 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 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 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 boolean checkInvariants(TreeNode t) { TreeNode tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode )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; } }



