/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* 基于哈希表的<tt>Map</tt>接口实现。此实现提供所有可选的映射操作,并允许<tt>null</tt>值和<tt>null</tt>键。
* (<tt>HashMap</tt>类大致相当于<tt>Hashtable</tt>,不过它是非同步的,并且允许空值。)该类不保证映射的顺序;
* 特别是,它不保证随时间的推移顺序将保持不变。
*
* <p>此实现对基本操作(<tt>get</tt>和<tt>put</tt>)提供恒定时间性能,假设哈希函数在桶之间适当地分散元素。
* 对集合视图的迭代需要与<tt>HashMap</tt>实例的“容量”(桶的数量)和其大小(键值映射的数量)成比例的时间。
* 因此,如果迭代性能很重要,不要将初始容量设置得太高(或负载因子太低)非常重要。
*
* <p><tt>HashMap</tt>的一个实例有两个影响其性能的参数:<i>初始容量</i>和<i>负载因子</i>。
* <i>容量</i>是哈希表中的桶数,初始容量只是哈希表创建时的容量。
* <i>负载因子</i>是哈希表被允许在其容量自动增加之前变得多满的度量。
* 当哈希表中的条目数超过负载因子和当前容量的乘积时,哈希表就会<i>重新哈希</i>(即,内部数据结构会被重建),
* 以便哈希表有大约两倍的桶数。
*
* <p>一般来说,默认负载因子(0.75)在时间和空间成本之间提供了良好的平衡。
* 较高的值会减少空间开销,但会增加查找成本(反映在<tt>HashMap</tt>类的大多数操作中,包括<tt>get</tt>和<tt>put</tt>)。
* 在设置初始容量时,应考虑映射中的预期条目数及其负载因子,以最小化重新哈希操作的次数。
* 如果初始容量大于最大条目数除以负载因子,将永远不会进行重新哈希操作。
*
* <p>如果要在<tt>HashMap</tt>实例中存储许多映射,使用足够大的容量创建它将使映射比让其按需执行自动重新哈希效率更高。
* 请注意,使用具有相同{@code hashCode()}的许多键是减慢任何哈希表性能的肯定方法。
* 为减轻影响,当键是{@link Comparable}时,此类可能使用键之间的比较顺序来帮助解决冲突。
*
* <p><strong>请注意,此实现不是同步的。</strong>如果多个线程同时访问哈希映射,并且至少有一个线程在结构上修改了映射,
* 则<i>必须</i>在外部同步。结构修改是添加或删除一个或多个映射的任何操作;
* 仅改变实例已包含的键关联的值不是结构修改。通常通过在自然封装映射的某个对象上同步来实现此目的。
*
* 如果不存在这样的对象,则应使用{@link Collections#synchronizedMap Collections.synchronizedMap}方法“包装”映射。
* 这最好在创建时完成,以防止意外的非同步访问映射:<pre>
* Map m = Collections.synchronizedMap(new HashMap(...));</pre>
*
* <p>此类的所有“集合视图方法”返回的迭代器都是<i>快速失败</i>的:
* 如果在创建迭代器后的任何时候以任何方式(除了通过迭代器自己的<tt>remove</tt>方法之外)结构上修改了映射,
* 则迭代器将抛出{@link ConcurrentModificationException}。
* 因此,在并发修改的情况下,迭代器会迅速而干净地失败,而不是在未来某个不确定的时间冒险产生任意的非确定性行为。
*
* <p>请注意,迭代器的快速失败行为不能保证,因为在不同步的并发修改存在的情况下,通常无法对其进行硬性保证。
* 快速失败迭代器以尽力而为的方式抛出<tt>ConcurrentModificationException</tt>。
* 因此,依赖于此异常的程序的正确性是错误的:<i>迭代器的快速失败行为只应用于检测错误。</i>
*
* <p>此类是
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>的成员。
*
*
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
*
* @author Doug Lea
* @author Josh Bloch
* @author Arthur van Hoff
* @author Neal Gafter
* @see Object#hashCode()
* @see Collection
* @see Map
* @see TreeMap
* @see Hashtable
* @since 1.2
*/
public class TestHashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
private static final long serialVersionUID = 362498820763181265L;
/*
* 实现说明。
*
* 此映射通常充当分桶(bucketed)哈希表,但当桶变得太大时,它们被转换为TreeNodes的桶,
* 每个结构与java.util.TreeMap中的结构相似。大多数方法尝试使用普通桶,但在适用时(仅通过检查节点的instanceof)转发到TreeNode方法。
* TreeNodes的桶可以像任何其他桶一样遍历和使用,但在过度填充时还支持更快的查找。然而,
* 由于在正常使用中绝大多数桶都没有过度填充,检查树桶的存在可能会在表方法的过程中延迟。
*
* 树桶(即元素均为TreeNodes的桶)主要按hashCode排序,但在平局的情况下,如果两个元素属于相同的“class C implements Comparable<C>”类型,
* 则将使用它们的compareTo方法进行排序。为了验证这一点,我们通过反射谨慎检查泛型类型(参见方法comparableClassFor)。
* 树桶的增加复杂性在于提供了最坏情况下O(log n)操作,当键具有不同的哈希值或是可排序的时候。
* 因此,在hashCode()方法返回分布不均匀的值的意外或恶意用法,以及许多键共享hashCode的情况下,性能会逐渐降低,
* 只要它们也是Comparable。(如果这两者都不适用,与不采取预防措施相比,我们可能会浪费大约两倍的时间和空间。
* 但已知的唯一情况源于已经非常慢的用户编程实践,这几乎没有什么影响。)
*
* 由于TreeNodes的大小约为常规节点的两倍,仅在桶包含足够的节点时才使用它们(参见TREEIFY_THRESHOLD)。
* 并且当它们变得太小(由于移除或调整大小)时,它们会转换回普通桶。
* 在具有分布良好的用户hashCode的用法中,树桶很少被使用。理想情况下,在随机hashCode的情况下,
* 节点在桶中的频率遵循泊松分布(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
* 更多:小于千万分之一
*
* 树桶的根通常是其第一个节点。然而,有时(目前仅在Iterator.remove上),根可能在其他地方,
* 但可以通过遵循父链接(方法TreeNode.root())来恢复。
*
* 所有适用的内部方法都接受哈希码作为参数(通常由公共方法提供),允许它们相互调用而无需重新计算用户哈希码。
* 大多数内部方法还接受“tab”参数,通常是当前表,但在调整大小或转换时可能是新的或旧的。
*
* 当桶列表被转换为树状,拆分或取消树状时,我们保持它们在相同的相对访问/遍历顺序(即字段Node.next)中,
* 以更好地保持局部性,并稍微简化执行调用iterator.remove的拆分和遍历的处理。在插入时使用比较器,
* 以保持重新平衡时的总排序(或在此处所需的尽可能接近),我们将类和identityHashCodes进行比较作为
* 连接器。
*
* 在普通模式和树模式之间的使用和转换由于子类LinkedHashMap的存在而变得复杂。请参见下文,
* 定义用于在插入、移除和访问时调用的挂钩方法,允许LinkedHashMap内部在这些机制之外保持独立。
* (这还要求将地图实例传递给一些可能创建新节点的实用方法。)
*
* 类似于并发编程的SSA(静态单赋值)风格的编码风格有助于避免在所有复杂的指针操作中出现别名错误。
*/
/**
* 默认的初始容量 - 必须是2的幂。
*
* 这句话提到了HashMap的默认初始容量必须是2的幂。在HashMap的实现中,初始容量是哈希表中桶的数量,而选择2的幂作为初始容量有助于提高哈希函数的效果,使得元素更均匀地分布在桶中,减少哈希碰撞的可能性。这也有助于通过位运算更高效地计算元素的存储位置。
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
*
*
* 最大容量,如果在具有参数的任一构造函数中隐式指定了更高的值,则使用。
* 必须是小于或等于1<<30的2的幂。
*
*这段注释说明HashMap的最大容量限制。最大容量是一个防止意外情况下过大容量设置的保护措施。规定了最大容量必须是小于或等于1<<30的2的幂,以确保合理的内存使用和操作效率。
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 在构造函数中未指定时使用的负载因子。
*
* 这句话提到了在HashMap构造函数中未指定负载因子时使用的默认负载因子。负载因子是衡量哈希表充满程度的指标,通常用来控制在何时进行哈希表的重新调整大小。如果在构造HashMap对象时没有显式指定负载因子,则会使用默认的负载因子。在HashMap中,默认的负载因子通常是0.75,这被认为在时间和空间成本之间提供了一个良好的平衡。
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
*使用树而不是列表作为桶的阈值。当向具有至少此数量节点的桶添加元素时,桶将转换为树。该值必须大于2,并且应至少为8,以与关于在缩小时将树转换回普通桶的假设相一致。
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 在调整大小操作期间将(拆分的)桶取消树化的桶计数阈值。应该小于TREEIFY_THRESHOLD,并且最多为6,以与删除操作下的收缩检测相匹配。
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 可以树化桶的最小表容量。(否则,如果一个桶中的节点太多,表将被调整大小。)应该至少为4 * TREEIFY_THRESHOLD,以避免在调整大小和树化阈值之间发生冲突。
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* 基本的哈希桶节点,用于大多数条目。(请参阅下面的TreeNode子类以及LinkedHashMap中的Entry子类。)
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
java.util.HashMap.Node<K,V> next;
Node(int hash, K key, V value, java.util.HashMap.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()并将hash的高位(通过XOR运算)传播到低位。由于表使用2的幂掩码,仅在当前掩码上方的位中变化的哈希集将始终发生碰撞。
(已知的示例包括在小表中持有连续整数的Float键集。)因此,我们应用了一种将较高位的影响向下传播的转换。
在速度、实用性和位传播的质量之间存在权衡。由于许多常见的哈希集已经合理分布(因此不受传播的影响),并且因为我们使用树来处理桶中发生的大量碰撞,
我们只是以最便宜的方式对一些位进行了XOR运算,以减少系统损失,并将最高位的影响合并到索引计算中,否则由于表边界而永远不会使用
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* 如果x的形式是 "class C implements Comparable<C>",则返回x的类;否则返回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的幂。(我们在某些操作中也容忍长度为零,以允许目前不需要的引导机制。)
*/
transient java.util.HashMap.Node<K,V>[] table;
/**
* 保存缓存的entrySet()。请注意,AbstractMap字段用于keySet()和values().
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* 此地图中包含的键值映射的数量。
*/
transient int size;
/**
* HashMap已结构性修改的次数。结构性修改是指改变HashMap中的映射数量或以其他方式修改其内部结构(例如,rehash)的操作。此字段用于使HashMap的Collection视图上的迭代器快速失败(参见ConcurrentModificationException)。
*/
transient int modCount;
/**
* 下一次调整大小的大小值(容量 * 负载因子)。
*
* @serial
*/
//(在序列化时,javadoc描述是正确的。此外,如果尚未分配表数组,则此字段保存初始数组容量,或者为零表示DEFAULT_INITIAL_CAPACITY。)
int threshold;
/**
* 哈希表的负载因子。
*
* @serial
*/
final float loadFactor;
/* ---------------- Public operations -------------- */
/**
* 用指定的初始容量和负载因子构造一个空的HashMap。
*
* @param initialCapacity 初始容量
* @param loadFactor 负载因子
* @throws IllegalArgumentException 如果初始容量为负或负载因子为非正数
*/
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;
this.threshold = tableSizeFor(initialCapacity);
}
/**
* 用指定的初始容量和默认负载因子(0.75)构造一个空的HashMap。
*
* @param initialCapacity 初始容量
* @throws IllegalArgumentException 如果初始容量为负数
*/
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中的映射的初始容量创建。
*
* @param m 要放入此映射中的映射
* @throws NullPointerException 如果指定的映射为null
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
/**
* 实现Map.putAll和Map构造函数
*
* @param m 要复制的映射
* @param evict 当初始构造此映射时为false,否则为true(传递给afterNodeInsertion方法)
*/
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
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);
}
}
}
/**
* 返回此映射中键值映射的数量。
*
* @return 此映射中键值映射的数量
*/
public int size() {
return size;
}
/**
* 如果此映射不包含键值映射,则返回true。
*
* @return 如果此映射不包含键值映射,则返回true
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 返回指定键映射到的值,如果此映射不包含键的映射,则返回null。
*
* <p>更正式地说,如果此映射包含从键{@code k}到值{@code v}的映射,使得{@code (key==null ? k==null :
* key.equals(k))},则此方法返回{@code v};否则返回{@code null}。 (最多可以有一个这样的映射。)
*
* <p>返回值为{@code null}不一定表示映射不包含键的映射;还可能是映射明确将键映射到{@code null}。可以使用{@link #containsKey containsKey}操作来区分这两种情况。
*
* @see #put(Object, Object)
*/
public V get(Object key) {
java.util.HashMap.Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* 实现Map.get和相关方法
*
* @param hash 键的哈希值
* @param key 键
* @return 节点,如果没有则返回null
*/
final java.util.HashMap.Node<K,V> getNode(int hash, Object key) {
java.util.HashMap.Node<K,V>[] tab; java.util.HashMap.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 java.util.HashMap.TreeNode)
return ((java.util.HashMap.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。
*
* @param key 要测试其在此映射中是否存在的键
* @return 如果此映射包含指定键的映射,则返回true。
*/
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
/**
* 在此映射中将指定的值与指定的键关联。如果映射先前包含键的映射,则旧值将被替换。
*
* @param key 要与指定值关联的键
* @param value 要与指定键关联的值
* @return 与<tt>key</tt>关联的先前值,如果<tt>key</tt>没有映射则返回<tt>null</tt>。
* (<tt>null</tt>的返回值还可能表示映射先前将<tt>null</tt>与<tt>key</tt>关联。)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* 实现Map.put和相关方法
*
* @param hash 键的哈希值
* @param key 键
* @param value 要放入的值
* @param onlyIfAbsent 如果为true,则不更改现有值
* @param evict 如果为false,则表处于创建模式。
* @return 先前的值,如果没有则返回null
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
java.util.HashMap.Node<K,V>[] tab; java.util.HashMap.Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
java.util.HashMap.Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof java.util.HashMap.TreeNode)
e = ((java.util.HashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
/**
* 初始化或加倍表大小。如果为null,则根据字段threshold中持有的初始容量目标进行分配。
* 否则,因为我们使用的是2的幂扩展,每个桶中的元素要么保持在相同的索引处,要么在新表中以2的幂偏移移动。
*
* @return 表
*/
final java.util.HashMap.Node<K,V>[] resize() {
java.util.HashMap.Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
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
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
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"})
java.util.HashMap.Node<K,V>[] newTab = (java.util.HashMap.Node<K,V>[])new java.util.HashMap.Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
java.util.HashMap.Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof java.util.HashMap.TreeNode)
((java.util.HashMap.TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
java.util.HashMap.Node<K,V> loHead = null, loTail = null;
java.util.HashMap.Node<K,V> hiHead = null, hiTail = null;
java.util.HashMap.Node<K,V> next;
do {
next = e.next;
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;
}
/**
* 替换给定哈希值的索引处的桶中的所有链接节点,除非表太小,在这种情况下进行调整大小。
*/
final void treeifyBin(java.util.HashMap.Node<K,V>[] tab, int hash) {
int n, index; java.util.HashMap.Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
java.util.HashMap.TreeNode<K,V> hd = null, tl = null;
do {
java.util.HashMap.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);
}
}
/**
* 将指定映射中的所有映射复制到此映射。这些映射将替换此映射当前对指定映射中任何键的任何映射。
*
* @param m 要存储在此映射中的映射
* @throws NullPointerException 如果指定的映射为null
*/
public void putAll(Map<? extends K, ? extends V> m) {
putMapEntries(m, true);
}
/**
* 如果存在,从此映射中删除指定键的映射。
*
* @param key 要从映射中删除其映射的键
* @return 与<tt>key</tt>关联的先前值,如果<tt>key</tt>没有映射则返回<tt>null</tt>。
* (<tt>null</tt>的返回值还可能表示映射先前将<tt>null</tt>与<tt>key</tt>关联。)
*/
public V remove(Object key) {
java.util.HashMap.Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
/**
* 实现Map.remove和相关方法
*
* @param hash 键的哈希值
* @param key 键
* @param value 如果matchValue为true,则匹配的值,否则忽略
* @param matchValue 如果为true,仅在值相等时删除
* @param movable 如果为false,则在删除时不移动其他节点
* @return 节点,如果没有则返回null
*/
final java.util.HashMap.Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
java.util.HashMap.Node<K,V>[] tab; java.util.HashMap.Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
java.util.HashMap.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 java.util.HashMap.TreeNode)
node = ((java.util.HashMap.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 java.util.HashMap.TreeNode)
((java.util.HashMap.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() {
java.util.HashMap.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。
*
* @param value 要测试其在此映射中是否存在的值
* @return 如果此映射将一个或多个键映射到指定值,则返回true
*/
public boolean containsValue(Object value) {
java.util.HashMap.Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
for (int i = 0; i < tab.length; ++i) {
for (java.util.HashMap.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;
}
/**
* 返回此映射中包含的键的{@link Set}视图。该集合由映射支持,因此对映射的更改会反映在集合中,反之亦然。
* 如果在集合上进行迭代时修改映射(除非通过迭代器自己的<tt>remove</tt>操作),迭代的结果是未定义的。
* 该集合支持元素移除,通过<tt>Iterator.remove</tt>、<tt>Set.remove</tt>、<tt>removeAll</tt>、<tt>retainAll</tt>和<tt>clear</tt>操作从映射中删除相应的映射。
* 它不支持<tt>add</tt>或<tt>addAll</tt>操作。
*
* @return 包含在此映射中的键的集合视图
*/
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new java.util.HashMap.KeySet();
keySet = ks;
}
return ks;
}
final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { java.util.HashMap.this.clear(); }
public final Iterator<K> iterator() { return new java.util.HashMap.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 java.util.HashMap.KeySpliterator<>(java.util.HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super K> action) {
java.util.HashMap.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 (java.util.HashMap.Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
/**
* 返回此映射中包含的值的{@link Collection}视图。该集合由映射支持,因此对映射的更改会反映在集合中,反之亦然。
* 如果在集合上进行迭代时修改映射(除非通过迭代器自己的<tt>remove</tt>操作),迭代的结果是未定义的。
* 该集合支持元素移除,通过<tt>Iterator.remove</tt>、<tt>Collection.remove</tt>、<tt>removeAll</tt>、<tt>retainAll</tt>和<tt>clear</tt>操作从映射中删除相应的映射。
* 它不支持<tt>add</tt>或<tt>addAll</tt>操作。
*
* @return 包含在此映射中的值的视图
*/
public Collection<V> values() {
Collection<V> vs = values;
if (vs == null) {
vs = new java.util.HashMap.Values();
values = vs;
}
return vs;
}
final class Values extends AbstractCollection<V> {
public final int size() { return size; }
public final void clear() { java.util.HashMap.this.clear(); }
public final Iterator<V> iterator() { return new java.util.HashMap.ValueIterator(); }
public final boolean contains(Object o) { return containsValue(o); }
public final Spliterator<V> spliterator() {
return new java.util.HashMap.ValueSpliterator<>(java.util.HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super V> action) {
java.util.HashMap.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 (java.util.HashMap.Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
/**
* 返回此映射中包含的映射的{@link Set}视图。该集合由映射支持,因此对映射的更改会反映在集合中,反之亦然。
* 如果在集合上进行迭代时修改映射(除非通过迭代器自己的<tt>remove</tt>操作,或通过迭代器返回的映射条目上的<tt>setValue</tt>操作),
* 迭代的结果是未定义的。该集合支持元素移除,通过<tt>Iterator.remove</tt>、<tt>Set.remove</tt>、<tt>removeAll</tt>、<tt>retainAll</tt>和<tt>clear</tt>操作从映射中删除相应的映射。
* 它不支持<tt>add</tt>或<tt>addAll</tt>操作。
*
* @return 包含在此映射中的映射的集合视图
*/
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new java.util.HashMap.EntrySet()) : es;
}
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public final int size() { return size; }
public final void clear() { java.util.HashMap.this.clear(); }
public final Iterator<Map.Entry<K,V>> iterator() {
return new java.util.HashMap.EntryIterator();
}
public final boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
java.util.HashMap.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 java.util.HashMap.EntrySpliterator<>(java.util.HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
java.util.HashMap.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 (java.util.HashMap.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 JDK8 Map扩展方法的覆盖实现。
@Override
public V getOrDefault(Object key, V defaultValue) {
java.util.HashMap.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) {
java.util.HashMap.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) {
java.util.HashMap.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);
java.util.HashMap.Node<K,V>[] tab; java.util.HashMap.Node<K,V> first; int n, i;
int binCount = 0;
java.util.HashMap.TreeNode<K,V> t = null;
java.util.HashMap.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 java.util.HashMap.TreeNode)
old = (t = (java.util.HashMap.TreeNode<K,V>)first).getTreeNode(hash, key);
else {
java.util.HashMap.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();
java.util.HashMap.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);
java.util.HashMap.Node<K,V>[] tab; java.util.HashMap.Node<K,V> first; int n, i;
int binCount = 0;
java.util.HashMap.TreeNode<K,V> t = null;
java.util.HashMap.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 java.util.HashMap.TreeNode)
old = (t = (java.util.HashMap.TreeNode<K,V>)first).getTreeNode(hash, key);
else {
java.util.HashMap.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);
java.util.HashMap.Node<K,V>[] tab; java.util.HashMap.Node<K,V> first; int n, i;
int binCount = 0;
java.util.HashMap.TreeNode<K,V> t = null;
java.util.HashMap.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 java.util.HashMap.TreeNode)
old = (t = (java.util.HashMap.TreeNode<K,V>)first).getTreeNode(hash, key);
else {
java.util.HashMap.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) {
java.util.HashMap.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 (java.util.HashMap.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) {
java.util.HashMap.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 (java.util.HashMap.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();
}
}
/* ------------------------------------------------------------ */
// 克隆和序列化
/**
* 返回此<tt>HashMap</tt>实例的浅拷贝:键和值本身不会被克隆。
*
* @return 此映射的浅拷贝
*/
@SuppressWarnings("unchecked")
@Override
public Object clone() {
java.util.HashMap<K,V> result;
try {
result = (java.util.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;
}
/**
* 将<tt>HashMap</tt>实例的状态保存到流中(即,序列化它)。
*
* @serialData <tt>HashMap</tt>的<i>容量</i>(桶数组的长度)被写入(int),然后是<i>大小</i>(int,键值映射的数量),
* 然后是每个键值映射的键(Object)和值(Object)。键值映射按照没有特定顺序被写入。
*/
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);
}
/**
* 从流中重新构建<tt>HashMap</tt>实例(即,反序列化它)。
*/
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException {
// Read in the threshold (ignored), loadfactor, and any hidden stuff
s.defaultReadObject();
reinitialize();
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new InvalidObjectException("Illegal load factor: " +
loadFactor);
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) { // (if zero, use defaults)
// Size the table using given load factor only if within
// range of 0.25...4.0
float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f);
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);
@SuppressWarnings({"rawtypes","unchecked"})
java.util.HashMap.Node<K,V>[] tab = (java.util.HashMap.Node<K,V>[])new java.util.HashMap.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);
}
}
}
/* ------------------------------------------------------------ */
// iterators
abstract class HashIterator {
java.util.HashMap.Node<K,V> next; // next entry to return
java.util.HashMap.Node<K,V> current; // current entry
int expectedModCount; // for fast-fail
int index; // current slot
HashIterator() {
expectedModCount = modCount;
java.util.HashMap.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 java.util.HashMap.Node<K,V> nextNode() {
java.util.HashMap.Node<K,V>[] t;
java.util.HashMap.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() {
java.util.HashMap.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 java.util.HashMap.HashIterator
implements Iterator<K> {
public final K next() { return nextNode().key; }
}
final class ValueIterator extends java.util.HashMap.HashIterator
implements Iterator<V> {
public final V next() { return nextNode().value; }
}
final class EntryIterator extends java.util.HashMap.HashIterator
implements Iterator<Map.Entry<K,V>> {
public final Map.Entry<K,V> next() { return nextNode(); }
}
/* ------------------------------------------------------------ */
// spliterators
static class HashMapSpliterator<K,V> {
final java.util.HashMap<K,V> map;
java.util.HashMap.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(java.util.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) {
java.util.HashMap<K,V> m = map;
est = m.size;
expectedModCount = m.modCount;
java.util.HashMap.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 java.util.HashMap.HashMapSpliterator<K,V>
implements Spliterator<K> {
KeySpliterator(java.util.HashMap<K,V> m, int origin, int fence, int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}
public java.util.HashMap.KeySpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid || current != null) ? null :
new java.util.HashMap.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();
java.util.HashMap<K,V> m = map;
java.util.HashMap.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)) {
java.util.HashMap.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();
java.util.HashMap.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 java.util.HashMap.HashMapSpliterator<K,V>
implements Spliterator<V> {
ValueSpliterator(java.util.HashMap<K,V> m, int origin, int fence, int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}
public java.util.HashMap.ValueSpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid || current != null) ? null :
new java.util.HashMap.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();
java.util.HashMap<K,V> m = map;
java.util.HashMap.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)) {
java.util.HashMap.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();
java.util.HashMap.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 java.util.HashMap.HashMapSpliterator<K,V>
implements Spliterator<Map.Entry<K,V>> {
EntrySpliterator(java.util.HashMap<K,V> m, int origin, int fence, int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}
public java.util.HashMap.EntrySpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid || current != null) ? null :
new java.util.HashMap.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();
java.util.HashMap<K,V> m = map;
java.util.HashMap.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)) {
java.util.HashMap.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();
java.util.HashMap.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 {
java.util.HashMap.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
/*
* 以下的包保护方法设计为由LinkedHashMap覆盖,而不是由任何其他子类覆盖。几乎所有其他的内部方法也是包保护的,
* 但被声明为final,因此可以被LinkedHashMap、视图类和HashSet使用。
*/
// Create a regular (non-tree) node
java.util.HashMap.Node<K,V> newNode(int hash, K key, V value, java.util.HashMap.Node<K,V> next) {
return new java.util.HashMap.Node<>(hash, key, value, next);
}
// For conversion from TreeNodes to plain nodes
java.util.HashMap.Node<K,V> replacementNode(java.util.HashMap.Node<K,V> p, java.util.HashMap.Node<K,V> next) {
return new java.util.HashMap.Node<>(p.hash, p.key, p.value, next);
}
// Create a tree bin node
java.util.HashMap.TreeNode<K,V> newTreeNode(int hash, K key, V value, java.util.HashMap.Node<K,V> next) {
return new java.util.HashMap.TreeNode<>(hash, key, value, next);
}
// For treeifyBin
java.util.HashMap.TreeNode<K,V> replacementTreeNode(java.util.HashMap.Node<K,V> p, java.util.HashMap.Node<K,V> next) {
return new java.util.HashMap.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(java.util.HashMap.Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(java.util.HashMap.Node<K,V> p) { }
// Called only from writeObject, to ensure compatible ordering.
void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
java.util.HashMap.Node<K,V>[] tab;
if (size > 0 && (tab = table) != null) {
for (int i = 0; i < tab.length; ++i) {
for (java.util.HashMap.Node<K,V> e = tab[i]; e != null; e = e.next) {
s.writeObject(e.key);
s.writeObject(e.value);
}
}
}
}
/* ------------------------------------------------------------ */
// Tree bins
/**
* 这段注释说明了树形结构中的节点(Tree bins)的条目。它扩展了LinkedHashMap.Entry
* (LinkedHashMap.Entry本身又扩展了Node),因此可以作为常规节点或链接节点的扩展使用。
* @param <K>
* @param <V>
*/
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
java.util.HashMap.TreeNode<K,V> parent; // red-black tree links
java.util.HashMap.TreeNode<K,V> left;
java.util.HashMap.TreeNode<K,V> right;
java.util.HashMap.TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, java.util.HashMap.Node<K,V> next) {
super(hash, key, val, next);
}
/**
* Returns root of tree containing this node.
* 这段注释描述了一个方法的功能,即返回包含当前节点的树的根节点。在
* 树形结构中,每个节点都有一个根节点,通过这个方法可以获取到整个树的根节点。
*/
final java.util.HashMap.TreeNode<K,V> root() {
for (java.util.HashMap.TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
/**
* Ensures that the given root is the first node of its bin.
* 这段注释描述了一个操作的目的,即确保给定的根节点是其所在桶中的第一个节点。在哈希表的实现中,当一个桶中的元素数量很多时,
* 会将这些元素组织成一个树形结构。这个操作的目的是确保树的根节点在桶中是排在第一位的节点,可能是为了维护某种结构或方便后续的操作。
*/
static <K,V> void moveRootToFront(java.util.HashMap.Node<K,V>[] tab, java.util.HashMap.TreeNode<K,V> root) {
int n;
if (root != null && tab != null && (n = tab.length) > 0) {
int index = (n - 1) & root.hash;
java.util.HashMap.TreeNode<K,V> first = (java.util.HashMap.TreeNode<K,V>)tab[index];
if (root != first) {
java.util.HashMap.Node<K,V> rn;
tab[index] = root;
java.util.HashMap.TreeNode<K,V> rp = root.prev;
if ((rn = root.next) != null)
((java.util.HashMap.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 java.util.HashMap.TreeNode<K,V> find(int h, Object k, Class<?> kc) {
java.util.HashMap.TreeNode<K,V> p = this;
do {
int ph, dir; K pk;
java.util.HashMap.TreeNode<K,V> pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if (pl == null)
p = pr;
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}
/**
* Calls find for root node.
*/
final java.util.HashMap.TreeNode<K,V> 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;
}
/**
* Forms tree of the nodes linked from this node.
* 这段注释描述了一个操作的目的,即从当前节点开始,形成与该节点链接的节点的树形结构。在哈希表的实现中,
* 当一个桶中的元素数量较多时,可能会将这些元素组织成一个树,以提高查询性能。这个操作的目的是从当前节
* 点开始,通过节点之间的链接,形成一棵树。
* @return root of tree
*/
final void treeify(java.util.HashMap.Node<K,V>[] tab) {
java.util.HashMap.TreeNode<K,V> root = null;
for (java.util.HashMap.TreeNode<K,V> x = this, next; x != null; x = next) {
next = (java.util.HashMap.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 (java.util.HashMap.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);
java.util.HashMap.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);
}
/**
*这段注释描述了一个方法的功能,即返回一个由非树节点组成的列表,用以替换从当前节点链接的节点。
* 在哈希表的实现中,当一个桶中的元素数量较多且形成了树结构时,可能需要在某些情况下将树形结构
* 还原为普通的节点列表。这个方法的目的是返回一个不包含树节点的列表,用于替换当前节点链接的节点。
*/
final java.util.HashMap.Node<K,V> untreeify(java.util.HashMap<K,V> map) {
java.util.HashMap.Node<K,V> hd = null, tl = null;
for (java.util.HashMap.Node<K,V> q = this; q != null; q = q.next) {
java.util.HashMap.Node<K,V> p = map.replacementNode(q, null);
if (tl == null)
hd = p;
else
tl.next = p;
tl = p;
}
return hd;
}
/**
* Tree version of putVal.
*/
final java.util.HashMap.TreeNode<K,V> putTreeVal(java.util.HashMap<K,V> map, java.util.HashMap.Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
java.util.HashMap.TreeNode<K,V> root = (parent != null) ? root() : this;
for (java.util.HashMap.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) {
java.util.HashMap.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);
}
java.util.HashMap.TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
java.util.HashMap.Node<K,V> xpn = xp.next;
java.util.HashMap.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)
((java.util.HashMap.TreeNode<K,V>)xpn).prev = x;
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
/**
这段注释描述了一个方法的作用,即删除给定的节点,该节点在调用此方法之前必须存在。由于在树结构中,
我们不能像典型的红黑树删除代码那样交换内部节点的内容与通过"next"指针固定的叶子节点的内容(这些
指针在遍历过程中是独立可访问的),因此删除操作会更加复杂。因此,采用了一种通过交换树链接来实现的
方法。如果当前树的节点数量似乎太少,那么该桶将被转换回普通的桶(该测试在2到6个节点之间触发,具体
取决于树的结构)。
*/
final void removeTreeNode(java.util.HashMap<K,V> map, java.util.HashMap.Node<K,V>[] tab,
boolean movable) {
int n;
if (tab == null || (n = tab.length) == 0)
return;
int index = (n - 1) & hash;
java.util.HashMap.TreeNode<K,V> first = (java.util.HashMap.TreeNode<K,V>)tab[index], root = first, rl;
java.util.HashMap.TreeNode<K,V> succ = (java.util.HashMap.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 || root.right == null ||
(rl = root.left) == null || rl.left == null) {
tab[index] = first.untreeify(map); // too small
return;
}
java.util.HashMap.TreeNode<K,V> p = this, pl = left, pr = right, replacement;
if (pl != null && pr != null) {
java.util.HashMap.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
java.util.HashMap.TreeNode<K,V> sr = s.right;
java.util.HashMap.TreeNode<K,V> pp = p.parent;
if (s == pr) { // p was s's direct parent
p.parent = s;
s.right = p;
}
else {
java.util.HashMap.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) {
java.util.HashMap.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;
}
java.util.HashMap.TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);
if (replacement == p) { // detach
java.util.HashMap.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`方法中调用,关于拆分位和索引的详细讨
* 论请参见上文。
*
* 该方法接受以下参数:
* - `map`: 哈希表的实例。
* - `tab`: 用于记录桶头的表。
* - `index`: 正在拆分的表的索引。
* - `bit`: 在哈希上进行拆分的位。
*/
final void split(java.util.HashMap<K,V> map, java.util.HashMap.Node<K,V>[] tab, int index, int bit) {
java.util.HashMap.TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
java.util.HashMap.TreeNode<K,V> loHead = null, loTail = null;
java.util.HashMap.TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
for (java.util.HashMap.TreeNode<K,V> e = b, next; e != null; e = next) {
next = (java.util.HashMap.TreeNode<K,V>)e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
if (loHead != null) {
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {
tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}
/* ------------------------------------------------------------ */
// Red-black tree methods, all adapted from CLR
//这段注释说明了以下一组方法是红黑树的方法,所有这些方法都是从CLR(Cormen, Leiserson, Rivest)
// 算法书中适应而来的。在哈希表的实现中,红黑树通常用于优化具有大量元素的桶的性能。这些方法可能包括插入、
// 删除和平衡操作,以确保红黑树保持其平衡状态。
static <K,V> java.util.HashMap.TreeNode<K,V> rotateLeft(java.util.HashMap.TreeNode<K,V> root,
java.util.HashMap.TreeNode<K,V> p) {
java.util.HashMap.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> java.util.HashMap.TreeNode<K,V> rotateRight(java.util.HashMap.TreeNode<K,V> root,
java.util.HashMap.TreeNode<K,V> p) {
java.util.HashMap.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> java.util.HashMap.TreeNode<K,V> balanceInsertion(java.util.HashMap.TreeNode<K,V> root,
java.util.HashMap.TreeNode<K,V> x) {
x.red = true;
for (java.util.HashMap.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> java.util.HashMap.TreeNode<K,V> balanceDeletion(java.util.HashMap.TreeNode<K,V> root,
java.util.HashMap.TreeNode<K,V> x) {
for (java.util.HashMap.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 {
java.util.HashMap.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 {
java.util.HashMap.TreeNode<K,V> sl = xpl.left, sr = xpl.right;
if ((sl == null || !sl.red) &&
(sr == null || !sr.red)) {
xpl.red = true;
x = xp;
}
else {
if (sl == null || !sl.red) {
if (sr != null)
sr.red = false;
xpl.red = true;
root = rotateLeft(root, xpl);
xpl = (xp = x.parent) == null ?
null : xp.left;
}
if (xpl != null) {
xpl.red = (xp == null) ? false : xp.red;
if ((sl = xpl.left) != null)
sl.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateRight(root, xp);
}
x = root;
}
}
}
}
}
/**
* Recursive invariant check
*/
static <K,V> boolean checkInvariants(java.util.HashMap.TreeNode<K,V> t) {
java.util.HashMap.TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
tb = t.prev, tn = (java.util.HashMap.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;
}
}
}