java 集合類深入理解
阿新 • • 發佈:2018-12-23
2017-08-10
package collection.list;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* 基於hash 表實現的 Map 介面;此實現提供所有可選的對映操作,並允許使用null值和null鍵;
* (除了非同步和允許使用 null 之外,HashMap 類與 Hashtable 大致相同。)
* 此類不能保證對映順序;特別是該類不能保證該順序永恆不變.
* 此實現假定雜湊函式將元素適當地分佈在各桶之間,可為基本操作(get 和 put)提供穩定的效能
*
* 迭代 collection 檢視所需的時間與 HashMap 例項的“容量”(桶的數量)及其大小(鍵-值對映關係數)成比例。
* 所以,如果迭代效能很重要,則不要將初始容量設定得太高(或將載入因子設定得太低)。
*
* HashMap 的例項有兩個引數影響其效能:初始容量 和載入因子。
* 容量 是雜湊表中桶的數量,初始容量只是雜湊表在建立時的容量。
* 載入因子 是雜湊表在其容量自動增加之前可以達到多滿的一種尺度。
*
* ---------當雜湊表中的條目數超出了載入因子與當前容量的乘積時,則要對該雜湊表進行 rehash 操作(即重建內部資料結構),從而雜湊表將具有大約兩倍的桶數----------
*
* 通常,預設載入因子 (.75) 在時間和空間成本上尋求一種折衷。
* 載入因子過高雖然減少了空間開銷,但同時也增加了查詢成本(在大多數 HashMap 類的操作中,包括 get 和 put 操作,都反映了這一點)。
* 在設定初始容量時應該考慮到對映中所需的條目數及其載入因子,以便最大限度地減少 rehash 操作次數。如果初始容量大於最大條目數除以載入因子,則不會發生 rehash 操作。
*
* 如果很多對映關係要儲存在 HashMap 例項中,則相對於按需執行自動的 rehash 操作以增大表的容量來說,使用足夠大的初始容量建立它將使得對映關係能更有效地儲存。
*
* 注意,此實現不是同步的。
* 如果多個執行緒同時訪問一個雜湊對映,而其中至少一個執行緒從結構上修改了該對映,則它必須 保持外部同步。
* (結構上的修改是指新增或刪除一個或多個對映關係的任何操作;僅改變與例項已經包含的鍵關聯的值不是結構上的修改。)
* 這一般通過對自然封裝該對映的物件進行同步操作來完成。
*
* 如果不存在這樣的物件,則應該使用 Collections.synchronizedMap 方法來“包裝”該對映。
* 最好在建立時完成這一操作,以防止對對映進行意外的非同步訪問,如下所示:
* Map m = Collections.synchronizedMap(new HashMap(...));
*
* 由所有此類的“collection 檢視方法”所返回的迭代器都是快速失敗 的:
* 在迭代器建立之後,如果從結構上對對映進行修改,除非通過迭代器本身的 remove 方法,
* 其他任何時間任何方式的修改,迭代器都將丟擲 ConcurrentModificationException。
* 因此,面對併發的修改,迭代器很快就會完全失敗,而不冒在將來不確定的時間發生任意不確定行為的風險。
*
* 注意,迭代器的快速失敗行為不能得到保證,一般來說,存在非同步的併發修改時,不可能作出任何堅決的保證。
* 快速失敗迭代器盡最大努力丟擲 ConcurrentModificationException。
* 因此,編寫依賴於此異常的程式的做法是錯誤的,正確做法是:迭代器的快速失敗行為應該僅用於檢測程式錯誤。
*
* Java Collections Framework
*
* @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 HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
private static final long serialVersionUID = 362498820763181265L;
/*
* (連結串列在超過一定的範圍之後會轉化成一個紅黑樹)
* 實現需注意:
*
* 本類通常是由桶組成的雜湊表,然而當桶的尺寸過大時,會將節點重構為TreeNode(每個節點類似java.util.TreeMap) .
* 大部分方法實現會判斷節點的instanceof,如果是TreeNode,則會採取不同的實現方式
* TreeNode元素支援普通元素的所有操作(對外透明),但提供更快的查詢速度,
* 然而,絕大多數工具箱在正常使用的情況不是數量過大的,在table方法的過程中定時檢查是否存在的樹形工具箱
*
* 包含TreeNode的桶首先按hashCode排序,在tie時如果實現了Comparable,則會根據Comparable決定順序
* (我們保守檢查泛型型別 通過反射來驗證這個 -- 參見comparableClassFor方法 )
* TreeNode機制使得在雜湊特性不好的情況下,也能保證最差O(log n)的時間效能 ,當 keys之間都是不同的雜湊 或者 是有序的
* 因此, 在意外或惡意用法 下 效能降低 : 在 hashCode()方法返回值的分佈很差,以及 那些在許多 keys 分享一個 hashCode,
* 只要他們還具有可比性.(如果這些應用,我們可能浪費了兩倍 相比與 採取預防措施.但是唯一已知的可能情況源於 糟糕的使用者程式設計實踐,如此緩慢以至於小的區別 )
*
* 由於TreeNode的尺寸是常規節點大約2倍,因此僅當桶的尺寸大於TREEIFY_THRESHOLD時才會使用TreeNode
* 如果TreeNode的尺寸減小到一定程度(由於remove或resize),還會重新變回普通節點 . 使用者一般使用均勻的hashcode,樹形工具箱是很少被使用.
* 如果雜湊值的隨機性較好,則桶的尺寸與桶數大致服從Poisson分佈,因此基本不會用到TreeNode
* (http://en.wikipedia.org/wiki/Poisson_distribution)
* 平均約0.5的引數為預設調整閾值為0.75,雖然有一個很大的差異,因為調整粒度.
*
* 忽視方差,預期出現的列表大小 k (exp(-0.5)* pow(0.5, k)/factorial(k))。第一個值是
*
* 0: 0.60653066
* 1: 0.30326533
* 2: 0.07581633
* 3: 0.01263606
* 4: 0.00157952
* 5: 0.00015795
* 6: 0.00001316
* 7: 0.00000094
* 8: 0.00000006
* more: less than 1 in ten million
* 更多 : 在1000w內小於1
*
* 一個TreeNode桶的根節點通常是第一個節點,但有些時候(目前只有Iterator.remove)也會是其他元素,
* 但是可以恢復後遵循父關聯(method TreeNode.root())
*
* 所有適用的內部方法接受一個 hashcode 作為引數(通常提供一個公共方法),允許他們來相互之間呼叫不在需要在計算使用者的hashCodes.
* 許多內部方法也接受一個"tab"引數,這是當前正常的table表情況,當調整或者轉換時,可能是新的或舊的
*
* 當桶列表發生建樹(treeify)、分裂、退化(untreeify)時,仍然維護其原先鏈結構(i.e., Node.next)
* 樹結構中按照hash值、Comparator、tie-breakers三層優先方式進行排序
*
* 樹結構與鏈結構的轉換在子類LinkedHashMap中會更復雜一些,本類中預留了一些回撥方法給LinkedHashMap
* 看以下 關聯方法 定義被呼叫下新增,刪除和訪問是允許 LinkedHashMap 內部的,否則保證獨立的結構
* (這也要求 map 例項 被傳遞給 相同的通用 可以建立新節點的方法.)
*
* The concurrent-programming-like SSA-based 程式碼風格 有助於避免混淆錯誤 在所有的 旋轉 指標操作.
*
*/
/**
* 預設初始容量 - 必須是2的冪
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // = 16
/**
* 最大容量, 如果使用一個大的值是隱式地指定通過建構函式的引數.
* 必須是2的冪 <= 1<<30 == 2^30
*/
static final int MAXIMUM_CAPACITY = 1 << 30; // = 1073741824
/**
* 裝載因子
* 當在建構函式的時候沒有指定的預設裝載因子
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 由連結串列轉換成樹的閾值
* 一個桶中bin(箱子)的儲存方式由連結串列轉換成樹的閾值
* 即當桶中bin的數量超過TREEIFY_THRESHOLD時使用樹來代替連結串列。預設值是8
*
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 由樹轉換成連結串列的閾值
* 當執行resize操作時,當桶中bin的數量少於UNTREEIFY_THRESHOLD時使用連結串列來代替樹。預設值是6
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 當桶中的bin被樹化時最小的hash表容量
* (如果沒有達到這個閾值,即hash表容量小於MIN_TREEIFY_CAPACITY,當桶中bin的數量太多時會執行resize擴容操作)
* 這個MIN_TREEIFY_CAPACITY的值至少是TREEIFY_THRESHOLD的4倍。
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* 基礎的桶節點(bin node),大部分Entry的實現類 (See below for TreeNode subclass, and in LinkedHashMap for its Entry subclass)
*/
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; }
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,並將高低16位元組異或(注意不是直接key.hashCode()拿來用)
*
* 由於容量是2的冪次, 僅高位不同的hashCode總會落到同一個桶(例如整數部分相同的若干浮點數) 發生碰撞.
* (著名的例子是 插入多數Float型 keys 在小table中保持連續的整數)
* 這使得原始的hashCode很可能造成不好的雜湊特性,因此通過xor操作將高位的影響擴散到低位
*
* 所以我們應用一個 改變 就是 更高 bits 向下 傳播的影響,之間的速度有一個權衡, 通常的, 和 有品質的 bit-spreading.
* 因為許多常見的 hashes 是已經合理的分佈(所以不要從傳播中獲益), 因為我們用樹來處理大型集箱的碰撞,
*
* 否則永遠不會使用 index 運算 因為表的界限.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* 通過反射判斷物件x是否實現Comparable<C>介面
*
* @return 如果實現了Comparable,返回x的實際型別,也就是Class<C>,否則返回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.compareTo(x),否則返回0
*
* @param kc 必須實現Comparable
* @param k 型別為kc
* @param x 型別無限制
*/
@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));
}
/**
* 返回不小於cap的最小的2的冪次
* 比如10,則返回16
* Returns a power of two size for the given target capacity.
*/
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的冪.
* (We also tolerate length zero in some operations to allow bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
/**
* entrySet()快取
* Holds cached entrySet(). Note that AbstractMap fields are used for keySet() and values().
*/
transient Set<Entry<K,V>> entrySet;
/**
* 實際元素個數
* The number of key-value mappings contained in this map.
*/
transient int size;
/**
* HashMap發生結構變更的計數器,結構變更包括增刪元素、rehash等,這個屬性為實現迭代子的fast-fail特性
*/
transient int modCount;
/**
* 下一個resize的元素個數 (capacity * load factor).
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated,
// this field holds the initial array capacity,
// or zero signifying 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; // 所有其他欄位還是預設
}
/**
* 構造一個對映關係與指定 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);
}
/**
* 將m的所有元素放入本物件,實現Map.putAll和建構函式
* Implements Map.putAll and Map constructor
*
* @param m the map
* @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。
*
* 更確切地講,如果此對映包含一個滿足 (key==null ? k==null : key.equals(k)) 的從 k 鍵到 v 值的對映關係,則此方法返回 v;否則返回 null。(最多隻能有一個這樣的對映關係。)
*
* 返回 null 值並不一定 表明該對映不包含該鍵的對映關係;也可能該對映將該鍵顯示地對映為 null。可使用 containsKey 操作來區分這兩種情況。
*
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* get的實現
*
* @param hash
* @param key the key
* @return the node 不存在返回 null
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; // table的快照
Node<K,V> first, e;
int n; K k;
// first = tab[(n - 1) & hash]是hash對應桶的第一個元素
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; // 第一個equal就直接返回了
// 否則如果是TreeNode就呼叫TreeNode的get,不是就直接根據.next遍歷桶
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
/**
* 如果此對映包含對於指定鍵的對映關係,則返回 true。
*
* @param key - 要測試其是否在此對映中存在的鍵
* @return 如果此對映包含對於指定鍵的對映關係,則返回 true。
*
*/
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
/**
* 在此對映中關聯指定值與指定鍵。如果該對映以前包含了一個該鍵的對映關係,則舊值被替換。
*
* @param key - 指定值將要關聯的鍵
* @param value - 指定鍵將要關聯的值
* @return 與 key 關聯的舊值;如果 key 沒有任何對映關係,則返回 null。(返回 null 還可能表示該對映之前將 null 與 key 關聯。)
*
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* put 方法的實現
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent true表示僅當key不存在的情況才執行put(不修改已存在的值)
* @param evict false表示建立過程中
* @return 如果原先包含key,則返回舊的value,否則返回null
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab;
Node<K,V> p;
int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
// 初始化情況
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
// key對應的桶不存在情況(key也必然不存在),new一個新node就行了
tab[i] = newNode(hash, key, value, null);
else {
// 桶存在情況
Node<K,V> e; // 表示key的(可能有的)現有節點
K k;
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p; // 第一個就是,直接拿過來
else if (p instanceof TreeNode)
// TreeNode情況
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 非TreeNode,迴圈遍歷桶
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) { // 確實沒有,new一個新node
p.next = newNode(hash, key, value, null);
// 如果桶的尺寸超過了TREEIFY_THRESHOLD,這個桶要轉化為樹
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) { // 所有的已存在情況,更新value並返回舊value
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e); // 子類回撥
return oldValue;
}
}
// 到這說明新加了節點,modCount+1
// 注意這裡只處理增加節點,如果觸發resize或者treeify,會在對應方法裡繼續維護modCount
++modCount;
if (++size > threshold) // size超過閾值,觸發resize
resize();
afterNodeInsertion(evict); // 子類回撥
return null;
}
/**
* 初始化或擴容
*
* 由於容量是2的冪次,resize後元素下標或者不變,或者增加2的冪次
*
* @return 擴容後的表
*/
final Node<K,V>[] resize() {
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) // 擴容,容量*2
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // 初始容量是放置在閾值
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 更新threshold
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<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) { // 移動舊錶的元素
// 複製元素,重新進行hash
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null; // 舊錶置null以便空間快速回收
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e; // 只有一個元素的桶,直接扔到新的桶(新桶一定是空的)
else if (e instanceof TreeNode) // 處理TreeNode分裂
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // 普通的桶,逐個處理
Node<K,V> loHead = null, loTail = null; // 原桶的首位指標
Node<K,V> hiHead = null, hiTail = null; // 新桶(+oldCap)的首位指標
Node<K,V> next;
// 將同一桶中的元素根據(e.hash & oldCap)是否為0進行分割,分成兩個不同的連結串列,完成rehash
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;
}
/**
* 將指定的桶轉化為TreeNode
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do { // 先把Node連結串列轉成TreeNode連結串列
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 與 key 關聯的舊值;如果 key 沒有任何對映關係,則返回 null。(返回 null 還可能表示該對映之前將 null 與 key 關聯。)
*/
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value;
}
/**
* 刪除節點實現
*
* @param hash
* @param key
* @param value 如果matchValue=true,表示匹配的value,否則無作用
* @param matchValue true表示僅當key對應value等於matchValue時才刪除
* @param movable false表示不移動其他元素(迭代子使用)
* @return 如果刪了,返回被刪的元素,否則返回null
*/
final Node<K,V> removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
node = p; // 第一個就匹配,直接就他了
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else { // 否則遍歷連結串列找
do {
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) {// 這條件表示確實要刪
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount; // 刪除元素造成的結構變更
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
/**
* 從此對映中移除所有對映關係。此呼叫返回後,對映將為空。
*/
public void clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null; // 所有的桶都置為null
}
}
/**
* 如果此對映將一個或多個鍵對映到指定值,則返回 true。
*
* @param value - 要測試其是否在此對映中存在的值
* @return 如果此對映將一個或多個鍵對映到指定值,則返回 true
*
*/
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value || (value != null && value.equals(v)))
return true;
}
}
}
return false;
}
/**
* 返回此對映中所包含的鍵的 Set 檢視。該 set 受對映的支援,所以對對映的更改將反映在該 set 中,反之亦然。
* 如果在對 set 進行迭代的同時修改了對映(通過迭代器自己的 remove 操作除外),則迭代結果是不確定的。
* 該 set 支援元素的移除,通過 Iterator.remove、 Set.remove、 removeAll、 retainAll 和 clear 操作可從該對映中移除相應的對映關係。
* 它不支援 add 或 addAll 操作。
*
*
* @return 此對映中包含的鍵的 set 檢視
*/
public Set<K> keySet() {
Set<K> ks;
return (ks = keySet) == null ? (keySet = new KeySet()) : ks;
}
final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<K> iterator() { return new KeyIterator(); }
public final boolean contains(Object o) { return containsKey(o); }
public final boolean remove(Object key) {
return removeNode(hash(key), key, null, false, true) != null;
}
public final Spliterator<K> spliterator() {
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
/**
* 返回此對映所包含的值的 Collection 檢視。
* 該 collection 受對映的支援,所以對對映的更改將反映在該 collection 中,反之亦然。
* 如果在對 collection 進行迭代的同時修改了對映(通過迭代器自己的 remove 操作除外),則迭代結果是不確定的。
* 該 collection 支援元素的移除,通過 Iterator.remove、 Collection.remove、 removeAll、 retainAll 和 clear 操作可從該對映中移除相應的對映關係。
* 它不支援 add 或 addAll 操作。
*
* @return 此對映中包含的值的 collection 檢視
*/
public Collection<V> values() {
Collection<V> vs;
return (vs = values) == null ? (values = new Values()) : vs;
}
final class Values extends AbstractCollection<V> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<V> iterator() { return new ValueIterator(); }
public final boolean contains(Object o) { return containsValue(o); }
public final Spliterator<V> spliterator() {
return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super V> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
/**
* 返回此對映所包含的對映關係的 Set 檢視。 該 set 受對映支援,所以對對映的更改將反映在此 set 中,反之亦然。
* 如果在對 set 進行迭代的同時修改了對映(通過迭代器自己的 remove 操作,或者通過在該迭代器返回的對映項上執行 setValue 操作除外),則迭代結果是不確定的。
* 該 set 支援元素的移除,通過 Iterator.remove、 Set.remove、 removeAll、 retainAll 和 clear 操作可從該對映中移除相應的對映關係。
* 它不支援 add 或 addAll 操作。
*
* @return a set view of the mappings contained in this map
*/
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
public final boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Node<K,V> candidate = getNode(hash(key), key);
return candidate != null && candidate.equals(e);
}
public final boolean remove(Object o) {
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
Object key = e.getKey();
Object value = e.getValue();
return removeNode(hash(key), key, value, true, true) != null;
}
return false;
}
public final Spliterator<Map.Entry<K,V>> spliterator() {
return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
// Overrides of JDK8 Map extension methods
@Override
public V getOrDefault(Object key, V defaultValue) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}
@Override
public V putIfAbsent(K key, V value) {
return putVal(hash(key), key, value, true, true);
}
@Override
public boolean remove(Object key, Object value) {
return removeNode(hash(key), key, value, true, true) != null;
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
Node<K,V> e; V v;
if ((e = getNode(hash(key), key)) != null &&
((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
e.value = newValue;
afterNodeAccess(e);
return true;
}
return false;
}
@Override
public V replace(K key, V value) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) != null) {
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null;
}
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
if (mappingFunction == null)
throw new NullPointerException();
int hash = hash(key);
Node<K,V>[] tab; Node<K,V> first; int n, i;
int binCount = 0;
TreeNode<K,V> t = null;
Node<K,V> old = null;
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
if ((first = tab[i = (n - 1) & hash]) != null) {
if (first instanceof TreeNode)
old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
else {
Node<K,V> e = first; K k;
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
V oldValue;
if (old != null && (oldValue = old.value) != null) {
afterNodeAccess(old);
return oldValue;
}
}
V v = mappingFunction.apply(key);
if (v == null) {
return null;
} else if (old != null) {
old.value = v;
afterNodeAccess(old);
return v;
}
else if (t != null)
t.putTreeVal(this, tab, hash, key, v);
else {
tab[i] = newNode(hash, key, v, first);
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
}
++modCount;
++size;
afterNodeInsertion(true);
return v;
}
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if (remappingFunction == null)
throw new NullPointerException();
Node<K,V> e; V oldValue;
int hash = hash(key);
if ((e = getNode(hash, key)) != null &&
(oldValue = e.value) != null) {
V v = remappingFunction.apply(key, oldValue);
if (v != null) {
e.value = v;
afterNodeAccess(e);
return v;
}
else
removeNode(hash, key, null, false, true);
}
return null;
}
@Override
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if (remappingFunction == null)
throw new NullPointerException();
int hash = hash(key);
Node<K,V>[] tab; Node<K,V> first; int n, i;
int binCount = 0;
TreeNode<K,V> t = null;
Node<K,V> old = null;
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
if ((first = tab[i = (n - 1) & hash]) != null) {
if (first instanceof TreeNode)
old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
else {
Node<K,V> e = first; K k;
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
}
V oldValue = (old == null) ? null : old.value;
V v = remappingFunction.apply(key, oldValue);
if (old != null) {
if (v != null) {
old.value = v;
afterNodeAccess(old);
}
else
removeNode(hash, key, null, false, true);
}
else if (v != null) {
if (t != null)
t.putTreeVal(this, tab, hash, key, v);
else {
tab[i] = newNode(hash, key, v, first);
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
}
++modCount;
++size;
afterNodeInsertion(true);
}
return v;
}
@Override
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
if (value == null)
throw new NullPointerException();
if (remappingFunction == null)
throw new NullPointerException();
int hash = hash(key);
Node<K,V>[] tab; Node<K,V> first; int n, i;
int binCount = 0;
TreeNode<K,V> t = null;
Node<K,V> old = null;
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
if ((first = tab[i = (n - 1) & hash]) != null) {
if (first instanceof TreeNode)
old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
else {
Node<K,V> e = first; K k;
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
}
if (old != null) {
V v;
if (old.value != null)
v = remappingFunction.apply(old.value, value);
else
v = value;
if (v != null) {
old.value = v;
afterNodeAccess(old);
}
else
removeNode(hash, key, null, false, true);
return v;
}
if (value != null) {
if (t != null)
t.putTreeVal(this, tab, hash, key, value);
else {
tab[i] = newNode(hash, key, value, first);
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
}
++modCount;
++size;
afterNodeInsertion(true);
}
return value;
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key, e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
Node<K,V>[] tab;
if (function == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
e.value = function.apply(e.key, e.value);
}
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
/* ------------------------------------------------------------ */
// Cloning and serialization
/**
* 返回此 HashMap 例項的淺表副本:並不複製鍵和值本身。
*
* @return 此對映的淺表副本
*/
@SuppressWarnings("unchecked")
@Override
public Object clone() {
HashMap<K,V> result;
try {
result = (HashMap<K,V>)super.clone();
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
result.reinitialize();
result.putMapEntries(this, false);
return result;
}
// These methods are also used when serializing HashSets
final float loadFactor() { return loadFactor; }
final int capacity() {
return (table != null) ? table.length : (threshold > 0) ? threshold : DEFAULT_INITIAL_CAPACITY;
}
/**
* Save the state of the HashMap instance to a stream (i.e.,
* serialize it).
*
* @serialData The capacity of the HashMap (the length of the
* bucket array) is emitted (int), followed by the
* size (an int, the number of key-value
* mappings), followed by the key (Object) and value (Object)
* for each key-value mapping. The key-value mappings are
* emitted in no particular order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws IOException {
int buckets = capacity();
// Write out the threshold, loadfactor, and any hidden stuff
s.defaultWriteObject();
s.writeInt(buckets);
s.writeInt(size);
internalWriteEntries(s);
}
/**
* Reconstitute the {@code HashMap} instance from a stream (i.e.,
* deserialize it).
*/
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"})
Node<K,V>[] tab = (Node<K,V>[])new Node[cap];
table = tab;
// Read the keys and values, and put the mappings in the HashMap
for (int i = 0; i < mappings; i++) {
@SuppressWarnings("unchecked")
K key = (K) s.readObject();
@SuppressWarnings("unchecked")
V value = (V) s.readObject();
putVal(hash(key), key, value, false, false);
}
}
}
/* ------------------------------------------------------------ */
// iterators
abstract class HashIterator {
Node<K,V> next; // next entry to return
Node<K,V> current; // current entry
int expectedModCount; // for fast-fail
int index; // current slot
HashIterator() {
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) { // advance to first entry
do {} while (index < t.length && (next = t[index++]) == null);
}
}
public final boolean hasNext() {
return next != null;
}
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}
public final void remove() {
Node<K,V> p = current;
if (p == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
K key = p.key;
removeNode(hash(key), key, null, false, false);
expectedModCount = modCount;
}
}
final class KeyIterator extends HashIterator
implements Iterator<K> {
public final K next() { return nextNode().key; }
}
final class ValueIterator extends HashIterator
implements Iterator<V> {
public final V next() { return nextNode().value; }
}
final class EntryIterator extends HashIterator
implements Iterator<Map.Entry<K,V>> {
public final Map.Entry<K,V> next() { return nextNode(); }
}
/* ------------------------------------------------------------ */
// spliterators
static class HashMapSpliterator<K,V> {
final HashMap<K,V> map;
Node<K,V> current; // current node
int index; // current index, modified on advance/split
int fence; // one past last index
int est; // size estimate
int expectedModCount; // for comodification checks
HashMapSpliterator(HashMap<K,V> m, int origin,
int fence, int est,
int expectedModCount) {
this.map = m;
this.index = origin;
this.fence = fence;
this.est = est;
this.expectedModCount = expectedModCount;
}
final int getFence() { // initialize fence and size on first use
int hi;
if ((hi = fence) < 0) {
HashMap<K,V> m = map;
est = m.size;
expectedModCount = m.modCount;
Node<K,V>[] tab = m.table;
hi = fence = (tab == null) ? 0 : tab.length;
}
return hi;
}
public final long estimateSize() {
getFence(); // force init
return (long) est;
}
}
static final class KeySpliterator<K,V>
extends HashMapSpliterator<K,V>
implements Spliterator<K> {
KeySpliterator(HashMap<K,V> m, int origin, int fence, int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}
public KeySpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid || current != null) ? null :
new KeySpliterator<>(map, lo, index = mid, est >>>= 1,
expectedModCount);
}
public void forEachRemaining(Consumer<? super K> action) {
int i, hi, mc;
if (action == null)
throw new NullPointerException();
HashMap<K,V> m = map;
Node<K,V>[] tab = m.table;
if ((hi = fence) < 0) {
mc = expectedModCount = m.modCount;
hi = fence = (tab == null) ? 0 : tab.length;
}
else
mc = expectedModCount;
if (tab != null && tab.length >= hi &&
(i = index) >= 0 && (i < (index = hi) || current != null)) {
Node<K,V> p = current;
current = null;
do {
if (p == null)
p = tab[i++];
else {
action.accept(p.key);
p = p.next;
}
} while (p != null || i < hi);
if (m.modCount != mc)
throw new ConcurrentModificationException();
}
}
public boolean tryAdvance(Consumer<? super K> action) {
int hi;
if (action == null)
throw new NullPointerException();
Node<K,V>[] tab = map.table;
if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
while (current != null || index < hi) {
if (current == null)
current = tab[index++];
else {
K k = current.key;
current = current.next;
action.accept(k);
if (map.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
}
}
return false;
}
public int characteristics() {
return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
Spliterator.DISTINCT;
}
}
static final class ValueSpliterator<K,V>
extends HashMapSpliterator<K,V>
implements Spliterator<V> {
ValueSpliterator(HashMap<K,V> m, int origin, int fence, int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}
public ValueSpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid || current != null) ? null :
new ValueSpliterator<>(map, lo, index = mid, est >>>= 1,
expectedModCount);
}
public void forEachRemaining(Consumer<? super V> action) {
int i, hi, mc;
if (action == null)
throw new NullPointerException();
HashMap<K,V> m = map;
Node<K,V>[] tab = m.table;
if ((hi = fence) < 0) {
mc = expectedModCount = m.modCount;
hi = fence = (tab == null) ? 0 : tab.length;
}
else
mc = expectedModCount;
if (tab != null && tab.length >= hi &&
(i = index) >= 0 && (i < (index = hi) || current != null)) {
Node<K,V> p = current;
current = null;
do {
if (p == null)
p = tab[i++];
else {
action.accept(p.value);
p = p.next;
}
} while (p != null || i < hi);
if (m.modCount != mc)
throw new ConcurrentModificationException();
}
}
public boolean tryAdvance(Consumer<? super V> action) {
int hi;
if (action == null)
throw new NullPointerException();
Node<K,V>[] tab = map.table;
if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
while (current != null || index < hi) {
if (current == null)
current = tab[index++];
else {
V v = current.value;
current = current.next;
action.accept(v);
if (map.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
}
}
return false;
}
public int characteristics() {
return (fence < 0 || est == map.size ? Spliterator.SIZED : 0);
}
}
static final class EntrySpliterator<K,V>
extends HashMapSpliterator<K,V>
implements Spliterator<Map.Entry<K,V>> {
EntrySpliterator(HashMap<K,V> m, int origin, int fence, int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}
public EntrySpliterator<K,V> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid || current != null) ? null :
new EntrySpliterator<>(map, lo, index = mid, est >>>= 1,
expectedModCount);
}
public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
int i, hi, mc;
if (action == null)
throw new NullPointerException();
HashMap<K,V> m = map;
Node<K,V>[] tab = m.table;
if ((hi = fence) < 0) {
mc = expectedModCount = m.modCount;
hi = fence = (tab == null) ? 0 : tab.length;
}
else
mc = expectedModCount;
if (tab != null && tab.length >= hi &&
(i = index) >= 0 && (i < (index = hi) || current != null)) {
Node<K,V> p = current;
current = null;
do {
if (p == null)
p = tab[i++];
else {
action.accept(p);
p = p.next;
}
} while (p != null || i < hi);
if (m.modCount != mc)
throw new ConcurrentModificationException();
}
}
public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
int hi;
if (action == null)
throw new NullPointerException();
Node<K,V>[] tab = map.table;
if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
while (current != null || index < hi) {
if (current == null)
current = tab[index++];
else {
Node<K,V> e = current;
current = current.next;
action.accept(e);
if (map.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
}
}
return false;
}
public int characteristics() {
return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
Spliterator.DISTINCT;
}
}
/* ------------------------------------------------------------ */
// LinkedHashMap support
/*
* The following package-protected methods are designed to be
* overridden by LinkedHashMap, but not by any other subclass.
* Nearly all other internal methods are also package-protected
* but are declared final, so can be used by LinkedHashMap, view
* classes, and H