引言
哈希表是基於Map接口實現的實現類。 這個實現類提供所有可選的Map操作,並允許空值和空鍵。HashMap大致相當於Hashtable,區別之處在於它不是線程安全的,並且允許空值和空鍵。這個類不保證Map的順序,特別是,隨着時間的推移,Map的順序也會改變。
假設散列函數在桶之間正確地分散元素,此實現爲基本操作(get和put)提供了恆定時間性能。 對集合視圖的迭代需要與 HashMap實例的“容量”(桶數)加上其大小(鍵值映射的數量)成正比的時間。 因此,如果迭代性能很重要,則不要將初始容量設置得太高或負載因子太低,這點非常重要。
影響HashMap實例性能的參數有兩個:初始容量和負載因子。容量是是哈希表中的桶數,初始容量只是創建哈希表時的容量。負載因子是自動擴容之前,所能允許的最大度量係數。當哈希表中的桶數(元素數)超過負載因子和當前容量的乘積時,哈希表重新散列(即重建內部數據結構),導致哈希表大約有當前容量的兩倍。
一般來說,默認負載因子(0.75)在時間和空間成本之間提供了良好的權衡。較高的值會減少空間開銷,但會增加查找成本(反映在 HashMap類的大多數操作中,包括get和put)。 在設置其初始容量時,應考慮Map中的預期元素數及其負載因子,以便最小化重新散列操作的次數。 如果初始容量大於最大元素數除以負載因子,則不會發生重新散列操作。
如果要將多個映射存儲在HashMap實例中,則使用足夠大的容量創建Map,而不是按需自動執行重新散列來擴展表。請注意,如果多個鍵具有相同的HashCode,會降低任何哈希表的性能。爲了改善影響,Key最好能夠實現Comparable接口,這樣這個類就能在這些key之間使用比較來降低這種影響。
請注意,此實現不是線程安全的。如果多個線程同時訪問HashMap,並且至少有一個線程在結構上修改了Map,則必須在外部進行同步。(結構修改是添加或刪除一個或多個映射的任何操作;僅更改與實例已包含的鍵關聯的值不是結構修改。) 這通常通過同步封裝Map的某個對象來完成。
如果沒有這樣的對象(包含map的對象)存在,這個map應該使用Collections#synchronizedMap來封裝。爲了防止偶然異步訪問這個map,最好在創建的時候就完成封裝:
Map m = Collections.synchronizedMap(new HashMap(…));
 所有這個類的“集合視圖方法”返回的迭代器都是快速失敗的:如果在創建迭代器之後的任何時候對Map進行結構修改,除了通過迭代器自己的remove方法之外,迭代器將拋出一個{ConcurrentModificationException}。因此,面對併發修改,迭代器快速地響應失敗,而不是冒險在一個未來不確定的時間內任意的,非確定性的行爲。
請注意,無法保證迭代器的快速失敗行爲,一般來說,在存在不同步的併發修改時,不可能做出任何硬性保證。快速失敗迭代器會盡最大努力拋出ConcurrentModificationException。因此,編寫依賴於此異常的程序的正確性是錯誤的,迭代器的快速失敗行爲應該只用於檢測錯誤。
HashMap通常用作裝桶哈希表,但是當桶變得太大時,它們會被轉換爲TreeNodes結構的桶,每個桶的的結構與java.util.TreeMap中的結構類似。大多數方法嘗試使用普通的桶(鏈表中的桶),但是,如果適用,可以中繼到TreeNode結構(只需檢查節點的實例)。TreeNodes狀的桶可以像其他桶一樣遍歷和使用,它還支持過多填充時的快速查找。由於正常使用的大多數桶並沒有過度填充,所以在表方法的過程中可能會延遲檢查樹桶是否存在。
樹容器(即其元素都是TreeNode的容器)主要由hashCode排序,但在並列的情況下,如果兩個元素具有相同的Comparable實現,則使compareTo方法進行排序。(我們保守地通過反射檢查泛型類型來驗證這點 - 見方法comparableClassFor)。當鍵具有不同的哈希值或可排序時,樹桶的額外複雜性對於提供最壞情況的O(log n)操作是值得的。因此,在意外或惡意使用hashcode()方法返回分佈不均勻的值,以及許多鍵共享一個hashcode的情況下,只要它們是可比較的,性能就會優雅的降低。(如果這些都不適用,與不採取任何預防措施相比,我們可能在時間和空間上浪費大約兩倍。但是,唯一已知的案例源於糟糕的用戶編程實踐,這些實踐已經非常緩慢,以至於幾乎沒有什麼區別。)
由於TreeNodes的大小約爲常規節點的兩倍,因此只有當桶包含足夠的節點以保證使用時,我們才使用它們(請參閱TREEIFY_THRESHOLD)。當它們變得太小(由於移除或調整大小)時,它們會被轉換回普通的桶。在使用分佈均勻的用戶哈希代碼時,很少使用樹桶。理想情況下,在隨機散列下,桶中節點的頻率服從泊松分佈。(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: 少於千萬分之一
樹桶的根通常是它的第一個節點。但是,有時(目前僅在Iterator.remove上),根可能在其他地方,但可以在父鏈接之後恢復(方法TreeNode.root())。
所有適用的內部方法都接受hashCodes作爲參數(通常從公共方法提供),允許它們相互調用而無需重新計算hashCodes。 大多數內部方法也接受“tab”參數,通常是當前表,但在調整大小或轉換時可能是新的或舊的。
當桶列表被樹化,拆分或未樹化時,我們將它們保持在相同的相對訪問/遍歷順序(即,field Node.next)中以更好地保留局部性,並略微簡化對調用iterator.remove的拆分和遍歷的處理。 當在插入時使用比較器時,爲了保持整個重新排序的平衡性(或者在這裏需要儘可能接近),我們將類和identityHashCodes作爲綁定器進行比較。
普通模式vs樹模式之間的使用和轉換,由於子類LinkedHashMap的存在而變得複雜。 在插入、刪除和訪問時調用的鉤子方法,請參閱下面的定義,這些鉤子方法允許LinkedHashMap內部保持獨立於這些機制。 (這也要求將Map實例傳遞給可能創建新節點的一些實用程序方法。)
並行編程(如基於SSA的編碼樣式)有助於避免在所有扭曲指針操作中出現混疊錯誤。
源碼分析
/**
* 默認初始容量(16)-必須是2的冪
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 16
/**
*最大容量,當構造函數指定更大的值時,將使用此值替換。
*必須是二次冪<=1<<30。(1073741824)
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 系統默認的負載因子(如果構造函數中未指定)
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
*使用樹而不是桶的列表的計數閾值。 將元素添加到具有至少這麼多節點的桶時,
*列表被轉換爲樹。 該值必須大於2並且應該至少爲8,以符合樹中的元素移除後,樹收縮
*轉換回普通鏈表的假設。哈希碰撞後的鏈表上達到8個節點時要將鏈表重構爲紅黑樹,
*查詢的時間複雜度變爲O(logN)。
*/
static final int TREEIFY_THRESHOLD = 8;
/**
*紅黑樹節點轉換鏈表節點的閾值, 6個節點轉
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
*容器可以樹化的最小表容量。
*(否則,如果容器中的節點太多,則會調整表的大小。)
*應該至少爲4 * TREEIFY_THRESHOLD=32,以避免調整大小和樹化閾值之間的衝突。
*/
static final int MIN_TREEIFY_CAPACITY = 64;
Node節點
/**
*基本哈希元素節點,用於大多數元素。
*(參見下面的TreeNode子類,以及LinkedHashMap中的Entry子類。)
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
/**
*Node節點的hashCode值是有key和value的hashCode異或得到的
*/
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
/**
*判斷兩個node是否相等,如果指針相同則一定相等
*如果key指針相同或者key的equals方法相同並且value亦是如此,則兩個node相同
*/
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;
}
}
hash計算方式
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
key的hashCode值的高16位與低16位異或作爲key的最終hash值,h >>> 16表示無符號右移16位,高位補0,任何數跟0異或都是其本身,因此key的hash值高16位不變。這樣做的原因和HashMap中table的下標計算有關,
int n = tab.length;
int index = (n - 1) & hash;
HashMap數組的長度爲2的整次冪,因爲這樣數組長度減一正好相當於一個低位掩碼。“與”操作的結果就是散列值的高位全部歸零,只保留低位值,這樣取得數組下標總是在0~數組長度-1的區間內,因此這樣導致的後果,難免會帶來哈希碰撞。設計者權衡了speed, utility, and quality,將高16位與低16位異或來減少這種影響。設計者考慮到現在的hashCode分佈的已經很不錯了,而且當發生較大碰撞時也用樹形存儲降低了衝突。僅僅異或一下,既減少了系統的開銷,也不會造成的因爲高位沒有參與下標的計算(table長度比較小時),從而引起的碰撞。
/**
*檢查是否實現了Comparable接口,並且Comparable接口的泛型必須與類名一致
*Comparable<T>返回T.class
*/
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.compareTo(x),否則返回0
* (kc爲k所實現的Comparable接口的泛型類,comparableClassFor()方法返回的類名)
*/
static int compareComparables(Class<?> kc, Object k, Object x) {
return (x == null || x.getClass() != kc ? 0 :
((Comparable)k).compareTo(x));
}
/**
* 在實例化HashMap實例時,如果給定了initialCapacity,
* 由於HashMap的capacity都是2的冪,
* 因此這個方法用於找到大於等於initialCapacity的最小的2的冪
* (initialCapacity如果就是2的冪,則返回的還是這個數)。
* [算法解析](https://www.cnblogs.com/liujinhong/p/6576543.html)
*/
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;
}
成員變量
/**
* 該表在首次使用時初始化,並根據需要調整大小。 分配時,長度始終是2的冪。
*/
transient Node<K,V>[] table;
/**
* 返回此映射中包含的映射的Set視圖,因此對地圖的更改會反映在集合中,反之亦然。
*特別地,當在這個Set上進行迭代的過程中,
*如果修改了Map(除非是通過這個Set的迭代器進行remove()或setValue()操作),
*那麼迭代過程產生的結果是不確定的。
*該集合支持刪除操作,不支持添加操作
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* Map中包含的key-value鍵值對的數量.
*/
transient int size;
/**
* 結構修改的次數
* 結構修改是指更改HashMap中映射數量或以其他方式修改其內部結構(例如,重新散列)
*/
transient int modCount;
/**
* 下一次擴容時的臨界值(capacity * load factor)
*/
int threshold;
/**
* 負載因子
*/
final float loadFactor;
構造方法
/**
* 以給定的初始容量和負載因子構造一個空Map
*/
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;
//找到大於等於initialCapacity的最小的2的冪
this.threshold = tableSizeFor(initialCapacity);
}
/**
* 以給定的初始容量和默認的負載因子(0.75)構造一個空Map
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 以給定的初始容量(16)和默認的負載因子(0.75)構造一個空Map
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/**
* 以給定的Map和默認的負載因子(0.75)構造一個空Map
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
//計算新創建Map的初始容量。加1操作,避免創建的時候resize擴容
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
//獲取最終的2次冪容量
if (t > threshold)
threshold = tableSizeFor(t);
}
//如果map長度超過threshold的值,則擴容
else if (s > threshold)
resize();
//複製k-v鍵值對
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);
}
}
}
GET操作
/**
* 查找key,返回映射的value,如果未包含key,則返回null
* 獲取到null值時,也可能是value爲null
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
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) {
//hash值相等並且(key相等或者key.equal()相等),則返回此Node元素
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//如果沒有,則繼續往後檢查鏈表的下一個節點,直到遇到null節點
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;
}
樹結構
/* ------------------------------------------------------------ */
// Tree bins
/**
* TreeNode繼承了LinkedHashMap.Entry<K,V>,而後者又繼承了HashMap.Node<K,V>。
* 所以TreeNode既可以作爲Node使用,又因爲添加了prev前驅屬性,使得鏈表變成了雙向
*/
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; // 前節點(因爲TreeNode也是雙向鏈表結構)
boolean red;//是否是紅色
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
/**
* 返回包含此節點的樹結構的根節點
*/
final TreeNode<K,V> root() {
//循環查找父節點爲null的節點,即爲根節點
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
/**
* 把紅黑樹的根節點設爲其HashMap數組的第一個元素
* 保證樹的根節點一定也要成爲鏈表的首節點
*/
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
int n;
//根節點不爲空 並且 HashMap的元素數組不爲空
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;
//把此節點替換爲root節點
tab[index] = root;
//root的前節點
TreeNode<K,V> rp = root.prev;
//把root前節點與後節點相互關聯
//(把root從先前雙向鏈表中剝離出來,其前後節點再互相關聯)
if ((rn = root.next) != null)
((TreeNode<K,V>)rn).prev = rp;
if (rp != null)
rp.next = rn;
//把先前first節點的前節點指向root,再次把root加入雙向鏈表中
if (first != null)
first.prev = root;
root.next = first;
root.prev = null;
//以上操作並不會破壞樹結構
}
assert checkInvariants(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)//前節點的next不是當前節點
return false;
if (tn != null && tn.prev != t)//後節點的prev不是當前節點
return false;
//父節點的左右子節點都不是當前節點
if (tp != null && t != tp.left && t != tp.right)
return false;
//左子節點的父節點不是當前節點,或者左子節點hash大於當前節點的hash
if (tl != null && (tl.parent != t || tl.hash > t.hash))
return false;
//右子節點的父節點不是當前節點,或者右子節點hash小於當前節點的hash
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;
}
/**
* 從根節點this開始,以給定的hash值、key查找節點
* 注:紅黑樹左小右大
*
*/
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
//根節點對象調用find方法,將p設置爲根節點
TreeNode<K,V> p = this;
do {
int ph, dir; K pk;
TreeNode<K,V> pl = p.left, pr = p.right, q;
//如果p的hash值大於給定的hash值
//則將開始查找節點替換爲當前節點的左子節點
if ((ph = p.hash) > h)
p = pl;
//如果p的hash值小於給定的hash值
//則將開始查找節點替換爲當前節點的右子節點
else if (ph < h)
p = pr;
//如果p的hash值等於給定的hash值
//並且當前節點的key等於給定key或者key的equals方法相同
//則返回當前節點
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;
//如果key實現的Comparable的泛型類kc不爲空,
//則計算k.compareTo(pk)的值
//如果值小於0,則將查詢節重置爲左子節點
//如果值大於0,則將查詢節重置爲右子節點
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;
}
/**
* 以給定的hash值和key,從根節點開始查找.
*/
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
/**
* 用於在相等hashCodes和不可比較的情況下對插入進行排序。
* 用這個方法來比較兩個對象,返回值要麼大於0,要麼小於0,不會爲0
* 也就是說這一步一定能確定要插入的節點要麼是樹的左節點,要麼是右節點,
* 不然就無繼續滿足二叉樹結構了。
* 先比較兩個對象的類名,類名是字符串對象,就按字符串的比較規則
* 調用本地方法爲兩個對象生成hashCode值,再進行比較,hashCode相等的話返回-1 *
*/
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;
}
/**
* 從this節點開始將鏈表轉換成二叉樹
*/
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;
//如果根節點爲null,則對根節點賦值,
//紅黑樹的根節點爲黑色
if (root == null) {
x.parent = null;
x.red = false;
root = x;
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
//從根節點開始一直與當前節點比較,
//遇到子節點爲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;
//如果兩節點的key無法比較,
//則調用tieBreakOrder方法,強制比較
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;
}
}
}
}
//把紅黑樹的根節點設爲其HashMap數組的第一個元素
//保證樹的根節點一定也要成爲鏈表的首節點
moveRootToFront(tab, root);
}
/**
* Returns a list of non-TreeNodes replacing those linked from
* this node.
*/
final Node<K,V> untreeify(HashMap<K,V> map) {
Node<K,V> hd = null, tl = null;
for (Node<K,V> q = this; q != null; q = q.next) {
Node<K,V> p = map.replacementNode(q, null);
if (tl == null)
hd = p;
else
tl.next = p;
tl = p;
}
return hd;
}
/**
* Tree version of putVal.
*/
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this;
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
/**
* Removes the given node, that must be present before this call.
* This is messier than typical red-black deletion code because we
* cannot swap the contents of an interior node with a leaf
* successor that is pinned by "next" pointers that are accessible
* independently during traversal. So instead we swap the tree
* linkages. If the current tree appears to have too few nodes,
* the bin is converted back to a plain bin. (The test triggers
* somewhere between 2 and 6 nodes, depending on tree structure).
*/
final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
boolean movable) {
int n;
if (tab == null || (n = tab.length) == 0)
return;
int index = (n - 1) & hash;
TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
if (pred == null)
tab[index] = first = succ;
else
pred.next = succ;
if (succ != null)
succ.prev = pred;
if (first == null)
return;
if (root.parent != null)
root = root.root();
if (root == null || root.right == null ||
(rl = root.left) == null || rl.left == null) {
tab[index] = first.untreeify(map); // too small
return;
}
TreeNode<K,V> p = this, pl = left, pr = right, replacement;
if (pl != null && pr != null) {
TreeNode<K,V> s = pr, sl;
while ((sl = s.left) != null) // find successor
s = sl;
boolean c = s.red; s.red = p.red; p.red = c; // swap colors
TreeNode<K,V> sr = s.right;
TreeNode<K,V> pp = p.parent;
if (s == pr) { // p was s's direct parent
p.parent = s;
s.right = p;
}
else {
TreeNode<K,V> sp = s.parent;
if ((p.parent = sp) != null) {
if (s == sp.left)
sp.left = p;
else
sp.right = p;
}
if ((s.right = pr) != null)
pr.parent = s;
}
p.left = null;
if ((p.right = sr) != null)
sr.parent = p;
if ((s.left = pl) != null)
pl.parent = s;
if ((s.parent = pp) == null)
root = s;
else if (p == pp.left)
pp.left = s;
else
pp.right = s;
if (sr != null)
replacement = sr;
else
replacement = p;
}
else if (pl != null)
replacement = pl;
else if (pr != null)
replacement = pr;
else
replacement = p;
if (replacement != p) {
TreeNode<K,V> pp = replacement.parent = p.parent;
if (pp == null)
root = replacement;
else if (p == pp.left)
pp.left = replacement;
else
pp.right = replacement;
p.left = p.right = p.parent = null;
}
TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);
if (replacement == p) { // detach
TreeNode<K,V> pp = p.parent;
p.parent = null;
if (pp != null) {
if (p == pp.left)
pp.left = null;
else if (p == pp.right)
pp.right = null;
}
}
if (movable)
moveRootToFront(tab, r);
}
/**
* Splits nodes in a tree bin into lower and upper tree bins,
* or untreeifies if now too small. Called only from resize;
* see above discussion about split bits and indices.
*
* @param map the map
* @param tab the table for recording bin heads
* @param index the index of the table being split
* @param bit the bit of hash to split on
*/
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
for (TreeNode<K,V> e = b, next; e != null; e = next) {
next = (TreeNode<K,V>)e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
if (loHead != null) {
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {
tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}
/* ------------------------------------------------------------ */
// Red-black tree methods, all adapted from CLR
static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> r, pp, rl;
if (p != null && (r = p.right) != null) {
if ((rl = p.right = r.left) != null)
rl.parent = p;
if ((pp = r.parent = p.parent) == null)
(root = r).red = false;
else if (pp.left == p)
pp.left = r;
else
pp.right = r;
r.left = p;
p.parent = r;
}
return root;
}
static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> l, pp, lr;
if (p != null && (l = p.left) != null) {
if ((lr = p.left = l.right) != null)
lr.parent = p;
if ((pp = l.parent = p.parent) == null)
(root = l).red = false;
else if (pp.right == p)
pp.right = l;
else
pp.left = l;
l.right = p;
p.parent = l;
}
return root;
}
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
TreeNode<K,V> x) {
x.red = true;
for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (!xp.red || (xpp = xp.parent) == null)
return root;
if (xp == (xppl = xpp.left)) {
if ((xppr = xpp.right) != null && xppr.red) {
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.right) {
root = rotateLeft(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateRight(root, xpp);
}
}
}
}
else {
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.left) {
root = rotateRight(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateLeft(root, xpp);
}
}
}
}
}
}
static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
TreeNode<K,V> x) {
for (TreeNode<K,V> xp, xpl, xpr;;) {
if (x == null || x == root)
return root;
else if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (x.red) {
x.red = false;
return root;
}
else if ((xpl = xp.left) == x) {
if ((xpr = xp.right) != null && xpr.red) {
xpr.red = false;
xp.red = true;
root = rotateLeft(root, xp);
xpr = (xp = x.parent) == null ? null : xp.right;
}
if (xpr == null)
x = xp;
else {
TreeNode<K,V> sl = xpr.left, sr = xpr.right;
if ((sr == null || !sr.red) &&
(sl == null || !sl.red)) {
xpr.red = true;
x = xp;
}
else {
if (sr == null || !sr.red) {
if (sl != null)
sl.red = false;
xpr.red = true;
root = rotateRight(root, xpr);
xpr = (xp = x.parent) == null ?
null : xp.right;
}
if (xpr != null) {
xpr.red = (xp == null) ? false : xp.red;
if ((sr = xpr.right) != null)
sr.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateLeft(root, xp);
}
x = root;
}
}
}
else { // symmetric
if (xpl != null && xpl.red) {
xpl.red = false;
xp.red = true;
root = rotateRight(root, xp);
xpl = (xp = x.parent) == null ? null : xp.left;
}
if (xpl == null)
x = xp;
else {
TreeNode<K,V> sl = xpl.left, sr = xpl.right;
if ((sl == null || !sl.red) &&
(sr == null || !sr.red)) {
xpl.red = true;
x = xp;
}
else {
if (sl == null || !sl.red) {
if (sr != null)
sr.red = false;
xpl.red = true;
root = rotateLeft(root, xpl);
xpl = (xp = x.parent) == null ?
null : xp.left;
}
if (xpl != null) {
xpl.red = (xp == null) ? false : xp.red;
if ((sl = xpl.left) != null)
sl.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateRight(root, xp);
}
x = root;
}
}
}
}
}
}