package java.util;
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.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
public class HashMap extends AbstractMap
implements Map, Cloneable, Serializable {
//åºååID
private static final long serialVersionUID = 362498820763181265L;
//å叿¡¶æ°ç»çé»è®¤å®¹é
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//ç½ä¸å¾å¤æç« é½è¯´è¿ä¸ªå¼æ¯å叿¡¶æ°ç»è½å¤è¾¾å°çæå¤§å®¹éï¼å
¶å®è¿æ ·è¯´å¹¶ä¸åç¡®
//ä» resize() æ¹æ³çæ©å®¹æºå¶å¯ä»¥çåºæ¥ï¼HashMap æ¯æ¬¡æ©å®¹é½æ¯å°æ°ç»çç°æå®¹éå¢å¤§ä¸å
//å¦æç°æå®¹éå·²å¤§äºæçäº MAXIMUM_CAPACITY ï¼åä¸å
è®¸åæ¬¡æ©å®¹
//å¦åå³ä½¿æ¤æ¬¡æ©å®¹ä¼å¯¼è´å®¹éè¶
åº MAXIMUM_CAPACITY ï¼é£ä¹æ¯å
许ç
static final int MAXIMUM_CAPACITY = 1 << 30;
//è£
è½½å åçé»è®¤å¼
//è£
è½½å åç¨äºè§å®æ°ç»å¨èªå¨æ©å®¹ä¹åå¯ä»¥æ°æ®å æå
¶å®¹éçæé«æ¯ä¾ï¼å³å½æ°æ®éå ææ°ç»ç容éè¾¾å°è¿ä¸ªæ¯ä¾åï¼æ°ç»å°èªå¨æ©å®¹
//è£
è½½å åè¡¡éçæ¯ä¸ä¸ªæ£å表ç空é´ç使ç¨ç¨åº¦ï¼è´è½½å åè¶å¤§è¡¨ç¤ºæ£å表çè£
å¡«ç¨åº¦è¶é«ï¼å乿å°
//对äºä½¿ç¨é¾è¡¨çæ£å表æ¥è¯´ï¼æ¥æ¾ä¸ä¸ªå
ç´ ç平忶鴿¯O(1+a)ï¼å æ¤å¦æè´è½½å åè¶å¤§ï¼å对空é´çå©ç¨ç¨åº¦æ´é«ï¼ç¸å¯¹åºçæ¯æ¥æ¾æççéä½
//妿è´è½½å å太å°ï¼é£ä¹æ°ç»çæ°æ®å°è¿äºç¨çï¼å¯¹ç©ºé´çå©ç¨çä½
//宿¹é»è®¤çè´è½½å å为0.75ï¼æ¯å¹³è¡¡ç©ºé´å©ç¨çåè¿è¡æç两è
ä¹åçç»æ
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//ä¸ºäºæé«æçï¼å½é¾è¡¨çé¿åº¦è¶
åºè¿ä¸ªå¼æ¶ï¼å°±å°é¾è¡¨è½¬æ¢ä¸ºçº¢é»æ
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
//å叿¡¶æ°ç»ï¼å¨ç¬¬ä¸æ¬¡ä½¿ç¨æ¶æåå§å
//容éå¼åºæ¯2çæ´æ°å
transient Node[] table;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set> entrySet;
//Mapç大å°
transient int size;
//æ¯å½Mapçç»æåçååæ¶ï¼æ¤åæ°å°±ä¼éå¢
//å½å¨å¯¹Mapè¿è¡è¿ä»£æä½æ¶ï¼è¿ä»£å¨ä¼æ£æ¥æ¤åæ°å¼
//å¦ææ£æ¥å°æ¤åæ°çå¼åçååï¼å°±è¯´æå¨è¿ä»£çè¿ç¨ä¸Mapçç»æåçäºååï¼å æ¤ä¼ç´æ¥æåºå¼å¸¸
transient int modCount;
//æ°ç»çæ©å®¹ä¸´çç¹ï¼å½æ°ç»çæ°æ®éè¾¾å°è¿ä¸ªå¼æ¶å°±ä¼è¿è¡æ©å®¹æä½
//è®¡ç®æ¹æ³ï¼å½å容é x è£
è½½å å
int threshold;
//使ç¨çè£
è½½å åå¼
final float loadFactor;
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
*/
static final int MIN_TREEIFY_CAPACITY = 64;
//ç»ç¹
static class Node implements Map.Entry {
//å½åç»ç¹ç key çåå¸å¼
final int hash;
//é®
final K key;
//å¼
V value;
//ä¸ä¸ä¸ªç»ç¹
Node next;
Node(int hash, K key, V value, Node next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() {
return key;
}
public final V getValue() {
return value;
}
public final String toString() {
return key + "=" + value;
}
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 final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* Returns x's Class if it is of the form "class C implements
* Comparable", else 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;
}
/**
* Returns k.compareTo(x) if x matches kc (k's screened comparable
* class), else 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));
}
//æ ¹æ®åæ° cap è·åä¸ä¹ç¸è¿ç2ç广¬¡æ¹æ°, å 为 HashMap è¦æ±æ°ç»ç容éå¿
须为2ç广¬¡æ¹
//è¿åå¼ä¸ä¸å®ä¼æ¯ä¸ cap æè¿çå¶æ°å¼
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;
}
//设置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;
this.threshold = tableSizeFor(initialCapacity);
}
//设置Mapçåå§å大å°
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//é½ä½¿ç¨é»è®¤å¼
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
//ä¼ å
¥åå§æ°æ®
public HashMap(Map extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
/**
* Implements Map.putAll and Map constructor
*
* @param m the map
* @param evict false when initially constructing this map, else
* true (relayed to method afterNodeInsertion).
*/
final void putMapEntries(Map extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
//è¿æªè¿è¡è¿åå§å
if (table == null) {
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);
}
}
}
//è·åMapç大å°
public int size() {
return size;
}
//Mapæ¯å¦ä¸ºç©º
public boolean isEmpty() {
return size == 0;
}
//æ ¹æ® key å¼è·å Value
public V get(Object key) {
Node e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//æ¥æ¾æå®ç»ç¹
final Node getNode(int hash, Object key) {
Node[] tab;
Node first, e;
int n;
K k;
//åªæå½ table ä¸ä¸ºç©ºä¸ hash 对åºçä½ç½®ä¸ä¸º null ææå¯è·åçå
ç´ å¼
if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
//妿头ç»ç¹ç hash å¼ä¸ Key ä¸å¾
æå
¥æ°æ®ç¸ççè¯ï¼åè¯´ææ¾å°äºå¯¹åºå¼
if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
return first;
// != null 说æåå¨åå¸å²çª
if ((e = first.next) != null) {
//妿æ¯ç±çº¢é»æ æ¥å¤çåå¸å²çªï¼åç±æ¤æ¥æ¾ç¸åºç»ç¹
if (first instanceof TreeNode)
return ((TreeNode) first).getTreeNode(hash, key);
//éåé¾è¡¨
do {
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
//夿Mapæ¯å¦å
å«é®å¼ Key
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
//æå
¥æ°æ®
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent 为 true 表示ä¸ä¼è¦çæç¸å key çé null valueï¼å¦åä¼è¦çåæå¼
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node[] tab;
Node p;
int n, i;
//妿 table è¿æªåå§åï¼åè°ç¨ resize æ¹æ³è¿è¡åå§å
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//夿è¦åå
¥ç key æ¯å¦åå¨åå¸å²çªï¼çäº null 说æä¸åå¨å²çª
if ((p = tab[i = (n - 1) & hash]) == null)
//ç´æ¥å¨ç´¢å¼ i å¤æå»ºå
å«å¾
åå
¥å
ç´ çç»ç¹
tab[i] = newNode(hash, key, value, null);
else { //èµ°å
¥æ¬åæ¯ï¼è¯´æå¾
åå
¥ç key åå¨åå¸å²çª
Node e;
K k;
//p å¼å·²å¨ä¸ä¸ä¸ª if è¯å¥ä¸èµå¼äºï¼æ¤å¤å°±ç´æ¥æ¥å¤æ key å¼ä¹é´çç¸çæ§
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
//æåå²çªç头ç»ç¹
e = p;
//妿头ç»ç¹ç key ä¸å¾
æå
¥ç key ä¸ç¸çï¼ä¸å¤´ç»ç¹æ¯ TreeNode ç±»åï¼è¯´æè¯¥ hash 弿¯éç¨çº¢é»æ æ¥å¤çå²çª
else if (p instanceof TreeNode)
//å¦æçº¢é»æ°ä¸å
嫿ç¸å key çç»ç¹ï¼åè¿å该ç»ç¹ï¼å¦åè¿å null
e = ((TreeNode) p).putTreeVal(this, tab, hash, key, value);
else { //éç¨é¾è¡¨æ¥å¤ç hash å¼å²çª
for (int binCount = 0; ; ++binCount) {
//å½éåå°é¾è¡¨å°¾é¨æ¶
if ((e = p.next) == null) {
//æå»ºä¸ä¸ªæ°çç»ç¹æ·»å å°é¾è¡¨å°¾é¨
p.next = newNode(hash, key, value, null);
//妿é¾è¡¨çé¿åº¦å·²è¾¾å°å
许çæå¤§é¿åº¦ TREEIFY_THRESHOLD - 1 æ¶ï¼å°±å°é¾è¡¨è½¬æ¢ä¸ºçº¢é»æ
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//å½ e æåçç»ç¹ç key å¼ä¸å¾
æå
¥ç key ç¸çæ¶åè·³åºå¾ªç¯
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//妿 e != nullï¼è¯´æåå
å·²åå¨ç¸å key çé®
if (e != null) {
V oldValue = e.value;
//åªæå½ onlyIfAbsent 为 true ä¸ oldValue ä¸ä¸º null æ¶æä¸ä¼è¦çåæå¼
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//ç¨äº LinkedHashMap ï¼å¨ HashMap 䏿¯ç©ºå®ç°
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//å½å
ç´ æ°éè¾¾å°æ©å®¹ä¸´çç¹æ¶ï¼éè¦è¿è¡æ©å®¹
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//ç¨äºåå§å table æè
对ä¹è¿è¡æ©å®¹
//å¹¶è¿åæ°çæ°ç»
final Node[] resize() {
//æ©å®¹åçæ°ç»
Node[] oldTab = table;
//æ©å®¹åæ°ç»ç容é
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//æ©å®¹åMapçæ©å®¹ä¸´çå¼
int oldThr = threshold;
//æ©å®¹åæ°ç»ç容é忩容䏴çå¼
int newCap, newThr = 0;
if (oldCap > 0) {
//oldCap > 0 对åºçæ¯ table 已被åå§åçæ
åµï¼æ¤æ¶æ¯æ¥å¤ææ¯å¦éè¦è¿è¡æ©å®¹
//妿æ°ç»å·²è¾¾å°æå¤§å®¹éï¼åä¸åè¿è¡æ©å®¹ï¼å¹¶å°æ©å®¹ä¸´çç¹ threshold æåå° Integer.MAX_VALUEï¼ç»æ
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
} else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) {
//妿尿°ç»çç°æå®¹éæåå°ç°å¨ç两åä¾ç¶å°äºå
许çæå¤§å®¹éï¼èä¸ç°æå®¹éå¤§äºæçäºé»è®¤å®¹é
//åå°æ°ç»ç容é忩容䏴çå¼åæå为åå
ç两å
newThr = oldThr << 1;
}
//æ¤å¤åºè¯¥è¿æä¸ç§æ
åµ
//å³å°æ°ç»çç°æå®¹éæåå°ç°å¨ç两ååå¤§äº MAXIMUM_CAPACITY çæ
åµ
//æ¤æ¶ newThr çäº 0ï¼newCap çäº oldCap ç两åå¼
//æ¤å¤å¹¶æ²¡æå¯¹ newCap çæ°å¼è¿è¡è¿åï¼è¯´æ HashMap æ¯å
许æ©å®¹å容éè¶
åº MAXIMUM_CAPACITY ç
//åªæ¯å¨ç°æå®¹éè¶
åº MAXIMUM_CAPACITY åï¼ä¸å
è®¸åæ¬¡è¿è¡æ©å®¹
} else if (oldThr > 0) {
//oldCap <= 0 && oldThr > 0 对åºçæ¯ table è¿æªè¢«åå§åï¼ä¸å¨è°ç¨æé 彿°æ¶æä¼ å
¥åå§åå¤§å° initialCapacity æè
å
å«åå§æ°æ®ç Map çæ
åµ
//è¿å¯¼è´äº threshold 被èµå¼ (tableSizeFor æ¹æ³)
//æ¤æ¶å°±ç´æ¥å°Mapç容éæå为 thresholdï¼å¨åè¾¹éæ°è®¡ç®æ°çæ©å®¹ä¸´çå¼
newCap = oldThr;
} else {
//oldCap <= 0 && oldThr <= 0 对åºçæ¯ table è¿æªè¢«åå§åï¼ä¸è°ç¨çæ¯æ åæ°çæé 彿°
//æ¤æ¶å°±å° table ç容鿩å
å°é»è®¤å¼å¤§å°ï¼å¹¶ä½¿ç¨é»è®¤çè£
è½½å å弿¥è®¡ç®æ©å®¹ä¸´çå¼
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"})
Node[] newTab = (Node[]) new Node[newCap];
table = newTab;
//å¦ææ§æ°ç»ä¸åå¨å¼ï¼åéè¦å°å
¶ä¸çæ°æ®å¤å¶å°æ°æ°ç»ä¸
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node e;
if ((e = oldTab[j]) != null) {
//å°æ§æ°ç»ä¸çå¼ç¨åæ¢ï¼å¸®å©GCåæ¶
oldTab[j] = null;
//e.next == null 说æå
ç´ e 没æäº§ç hash å²çªï¼å æ¤å¯ä»¥ç´æ¥è½¬ç§»è¯¥å
ç´
if (e.next == null)
//计ç®å
ç´ e 卿°æ°ç»ä¸çä½ç½®
newTab[e.hash & (newCap - 1)] = e;
//e instanceof TreeNode 说æå
ç´ e æäº§ç hash å²çªï¼ä¸ä½¿ç¨çº¢é»æ 管çå²çªçå
ç´
else if (e instanceof TreeNode)
((TreeNode) e).split(this, newTab, j, oldCap);
//èµ°å
¥å¦ä¸åæ¯ï¼è¯´æå
ç´ e æäº§ç hash å²çªï¼ä¸ä½¿ç¨é¾è¡¨ç»ææ¥ç®¡çå²çªçå
ç´
else {
Node loHead = null, loTail = null;
Node hiHead = null, hiTail = null;
Node 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;
}
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
final void treeifyBin(Node[] tab, int hash) {
int n, index;
Node e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode hd = null, tl = null;
do {
TreeNode p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
/**
* Copies all of the mappings from the specified map to this map.
* These mappings will replace any mappings that this map had for
* any of the keys currently in the specified map.
*
* @param m mappings to be stored in this map
* @throws NullPointerException if the specified map is null
*/
public void putAll(Map extends K, ? extends V> m) {
putMapEntries(m, true);
}
/**
* Removes the mapping for the specified key from this map if present.
*
* @param key key whose mapping is to be removed from the map
* @return the previous value associated with key, or
* null if there was no mapping for key.
* (A null return can also indicate that the map
* previously associated null with key.)
*/
public V remove(Object key) {
Node e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
/**
* Implements Map.remove and related methods
*
* @param hash key çåå¸å¼
* @param key the key
* @param value key对åºçå¼ï¼åªæå½ matchValue 为 true æ¶æéè¦ä½¿ç¨å°ï¼å¦å忽ç¥è¯¥å¼
* @param matchValue å¦æä¸º true ï¼ååªæå½ Map ä¸åå¨æä¸ªé® equals key ä¸ value ç¸çæ¶æä¼ç§»é¤è¯¥å
ç´ ï¼å¦ååªè¦ key ç hash å¼ç¸çå°±ç´æ¥ç§»é¤è¯¥å
ç´
* @param movable if false do not move other nodes while removing
* @return the node, or null if none
*/
final Node removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node[] tab;
Node p;
int n, index;
//åªæå½ table ä¸ä¸ºç©ºä¸ hash 对åºçç´¢å¼ä½ç½®åå¨å¼æ¶ææå¯ç§»é¤ç对象
if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) {
Node node = null, e;
K k;
V v;
//妿ä¸å¤´ç»ç¹ç key ç¸ç
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) { //åå¨åå¸å²çª
//ç¨çº¢é»æ æ¥å¤çåå¸å²çª
if (p instanceof TreeNode)
//æ¥æ¾å¯¹åºç»ç¹
node = ((TreeNode) p).getTreeNode(hash, key);
else { //ç¨é¾è¡¨æ¥å¤çåå¸å²çª
do {
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//node != null 说æåå¨ç¸åºç»ç¹
//妿 matchValue 为 false ï¼åéè¿ä¹åç夿å¯ç¥æ¥æ¾å°çç»ç¹ç key ä¸ åæ° key çåå¸å¼ä¸å®ç¸çï¼æ¤å¤å°±å¯ä»¥ç´æ¥ç§»é¤ç»ç¹ node
//妿 matchValue 为 true ï¼åå½ value ç¸çæ¶æéè¦ç§»é¤è¯¥ç»ç¹
if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) {
if (node instanceof TreeNode) //对åºçº¢é»æ
((TreeNode) node).removeTreeNode(this, tab, movable);
else if (node == p) //å¯¹åº key ä¸å¤´ç»ç¹ç¸ççæ
åµï¼æ¤æ¶ç´æ¥å°æéç§»åä¸ä¸ä½å³å¯
tab[index] = node.next;
else //对åºçæ¯é¾è¡¨çæ
åµ
p.next = node.next;
++modCount;
--size;
//ç¨äº LinkedHashMap ï¼å¨ HashMap 䏿¯ç©ºå®ç°
afterNodeRemoval(node);
return node;
}
}
return null;
}
//æ¸
ç©ºæ°æ®
public void clear() {
Node[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}
//夿Map䏿¯å¦å
å«å¼ä¸º value çç»ç¹
public boolean containsValue(Object value) {
Node[] tab;
V v;
if ((tab = table) != null && size > 0) {
for (int i = 0; i < tab.length; ++i) {
for (Node e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}
/**
* Returns a {@link Set} view of the keys contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own remove operation), the results of
* the iteration are undefined. The set supports element removal,
* which removes the corresponding mapping from the map, via the
* Iterator.remove, Set.remove,
* removeAll, retainAll, and clear
* operations. It does not support the add or addAll
* operations.
*
* @return a set view of the keys contained in this map
*/
public Set keySet() {
Set ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
final class KeySet extends AbstractSet {
public final int size() {
return size;
}
public final void clear() {
HashMap.this.clear();
}
public final Iterator 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 spliterator() {
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer super K> action) {
Node[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
/**
* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa. If the map is
* modified while an iteration over the collection is in progress
* (except through the iterator's own remove operation),
* the results of the iteration are undefined. The collection
* supports element removal, which removes the corresponding
* mapping from the map, via the Iterator.remove,
* Collection.remove, removeAll,
* retainAll and clear operations. It does not
* support the add or addAll operations.
*
* @return a view of the values contained in this map
*/
public Collection values() {
Collection vs = values;
if (vs == null) {
vs = new Values();
values = vs;
}
return vs;
}
final class Values extends AbstractCollection {
public final int size() {
return size;
}
public final void clear() {
HashMap.this.clear();
}
public final Iterator iterator() {
return new ValueIterator();
}
public final boolean contains(Object o) {
return containsValue(o);
}
public final Spliterator spliterator() {
return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer super V> action) {
Node[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node e = tab[i]; e != null; e = e.next)
action.accept(e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
/**
* Returns a {@link Set} view of the mappings contained in this map.
* The set is backed by the map, so changes to the map are
* reflected in the set, and vice-versa. If the map is modified
* while an iteration over the set is in progress (except through
* the iterator's own remove operation, or through the
* setValue operation on a map entry returned by the
* iterator) the results of the iteration are undefined. The set
* supports element removal, which removes the corresponding
* mapping from the map, via the Iterator.remove,
* Set.remove, removeAll, retainAll and
* clear operations. It does not support the
* add or addAll operations.
*
* @return a set view of the mappings contained in this map
*/
public Set> entrySet() {
Set> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
final class EntrySet extends AbstractSet> {
public final int size() {
return size;
}
public final void clear() {
HashMap.this.clear();
}
public final Iterator> 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 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> spliterator() {
return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer super Map.Entry> action) {
Node[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node e = tab[i]; e != null; e = e.next)
action.accept(e);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
//è·å key 对åºçç»ç¹å¼ï¼å¦æä¸åå¨åè¿åé»è®¤å¼ defaultValue
@Override
public V getOrDefault(Object key, V defaultValue) {
Node 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 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 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[] tab;
Node first;
int n, i;
int binCount = 0;
TreeNode t = null;
Node 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) first).getTreeNode(hash, key);
else {
Node 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 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[] tab;
Node first;
int n, i;
int binCount = 0;
TreeNode t = null;
Node 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) first).getTreeNode(hash, key);
else {
Node 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[] tab;
Node first;
int n, i;
int binCount = 0;
TreeNode t = null;
Node 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) first).getTreeNode(hash, key);
else {
Node 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[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node e = tab[i]; e != null; e = e.next)
action.accept(e.key, e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
@Override
public void replaceAll(BiFunction super K, ? super V, ? extends V> function) {
Node[] 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 e = tab[i]; e != null; e = e.next) {
e.value = function.apply(e.key, e.value);
}
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
/* ------------------------------------------------------------ */
// Cloning and serialization
/**
* Returns a shallow copy of this HashMap instance: the keys and
* values themselves are not cloned.
*
* @return a shallow copy of this map
*/
@SuppressWarnings("unchecked")
@Override
public Object clone() {
HashMap result;
try {
result = (HashMap) 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;
}
//è·åMapçå½å容é
//å½ table å·²åå§åæ¶ï¼è¿å table çæ°ç»é¿åº¦
//å½ table è¿æªåå§åæ¶ï¼å¦æ threshold å¤§äº 0ï¼æ¤æ¶å¯¹åºçæ¯å¨è°ç¨æé 彿°æ¶æä¼ å
¥åå§å大å°ï¼å容éå³ä¸º threshold
//妿 threshold å°äº 0ï¼å®¹éå³ä¸ºé»è®¤å¼
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[] tab = (Node[]) 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 {
//current æåçä¸ä¸ä¸ªç»ç¹
Node next; // next entry to return
//å½åç»ç¹
Node current; // current entry
//ç¨äºå¤æMapçç»ææ¯å¦åçäºåå
int expectedModCount; // for fast-fail
//å½åç´¢å¼
int index; // current slot
HashIterator() {
expectedModCount = modCount;
Node[] 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 nextNode() {
Node[] t;
Node e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
//妿è·åå°ä¸ä¸ä¸ªç»ç¹åï¼åä¸ä¸ä¸ªç»ç¹ä¸º null
//åç§»å¨æ°ç»æ¸¸æ ï¼ç§»å¨å°é null çå
ç´ ç´¢å¼å¤ï¼table ä¸çå
ç´ å¹¶ä¸æ¯ä¸å®è¿ç»çï¼
if ((next = (current = e).next) == null && (t = table) != null) {
do {
} while (index < t.length && (next = t[index++]) == null);
}
return e;
}
//ç§»é¤ current æåçç»ç¹
public final void remove() {
Node 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;
}
}
//ç¨äºéå Key çè¿ä»£å¨
final class KeyIterator extends HashIterator
implements Iterator {
public final K next() {
return nextNode().key;
}
}
//ç¨äºéå value çè¿ä»£å¨
final class ValueIterator extends HashIterator
implements Iterator {
public final V next() {
return nextNode().value;
}
}
//ç¨äºéåé®å¼å¯¹çè¿ä»£å¨
final class EntryIterator extends HashIterator
implements Iterator> {
public final Map.Entry next() {
return nextNode();
}
}
/* ------------------------------------------------------------ */
// spliterators
static class HashMapSpliterator {
final HashMap map;
Node 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 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 m = map;
est = m.size;
expectedModCount = m.modCount;
Node[] 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
extends HashMapSpliterator
implements Spliterator {
KeySpliterator(HashMap m, int origin, int fence, int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}
public KeySpliterator 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 m = map;
Node[] 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 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[] 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
extends HashMapSpliterator
implements Spliterator {
ValueSpliterator(HashMap m, int origin, int fence, int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}
public ValueSpliterator 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 m = map;
Node[] 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 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[] 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
extends HashMapSpliterator
implements Spliterator> {
EntrySpliterator(HashMap m, int origin, int fence, int est,
int expectedModCount) {
super(m, origin, fence, est, expectedModCount);
}
public EntrySpliterator 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> action) {
int i, hi, mc;
if (action == null)
throw new NullPointerException();
HashMap m = map;
Node[] 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 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> action) {
int hi;
if (action == null)
throw new NullPointerException();
Node[] 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 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
//æå»ºç»ç¹
Node newNode(int hash, K key, V value, Node next) {
return new Node<>(hash, key, value, next);
}
// For conversion from TreeNodes to plain nodes
Node replacementNode(Node p, Node next) {
return new Node<>(p.hash, p.key, p.value, next);
}
// Create a tree bin node
TreeNode newTreeNode(int hash, K key, V value, Node next) {
return new TreeNode<>(hash, key, value, next);
}
// For treeifyBin
TreeNode replacementTreeNode(Node p, Node next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}
//æ¸
ç©ºæ°æ®ï¼éç½®å°åå§ç¶æ
//å¨ clone() å readObject() ä¸¤ä¸ªæ¹æ³ä¸è¢«è°ç¨
void reinitialize() {
table = null;
entrySet = null;
keySet = null;
values = null;
modCount = 0;
threshold = 0;
size = 0;
}
// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node p) {
}
void afterNodeInsertion(boolean evict) {
}
void afterNodeRemoval(Node p) {
}
// Called only from writeObject, to ensure compatible ordering.
void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
Node[] tab;
if (size > 0 && (tab = table) != null) {
for (int i = 0; i < tab.length; ++i) {
for (Node e = tab[i]; e != null; e = e.next) {
s.writeObject(e.key);
s.writeObject(e.value);
}
}
}
}
/* ------------------------------------------------------------ */
// Tree bins
/**
* Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
* extends Node) so can be used as extension of either regular or
* linked node.
*/
static final class TreeNode extends LinkedHashMap.Entry {
//ç¶äº²ç»ç¹
TreeNode parent;
//å·¦åæ
TreeNode left;
//å³åæ
TreeNode right;
TreeNode prev; // needed to unlink next upon deletion
//é¢è²å±æ§
boolean red;
TreeNode(int hash, K key, V val, Node next) {
super(hash, key, val, next);
}
/**
* Returns root of tree containing this node.
*/
final TreeNode root() {
for (TreeNode 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 void moveRootToFront(Node[] tab, TreeNode root) {
int n;
if (root != null && tab != null && (n = tab.length) > 0) {
int index = (n - 1) & root.hash;
TreeNode first = (TreeNode) tab[index];
if (root != first) {
Node rn;
tab[index] = root;
TreeNode rp = root.prev;
if ((rn = root.next) != null)
((TreeNode) rn).prev = rp;
if (rp != null)
rp.next = rn;
if (first != null)
first.prev = root;
root.next = first;
root.prev = null;
}
assert checkInvariants(root);
}
}
/**
* Finds the node starting at root p with the given hash and key.
* The kc argument caches comparableClassFor(key) upon first use
* comparing keys.
*/
final TreeNode find(int h, Object k, Class> kc) {
TreeNode p = this;
do {
int ph, dir;
K pk;
TreeNode pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if (pl == null)
p = pr;
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}
/**
* Calls find for root node.
*/
final TreeNode getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
/**
* Tie-breaking utility for ordering insertions when equal
* hashCodes and non-comparable. We don't require a total
* order, just a consistent insertion rule to maintain
* equivalence across rebalancings. Tie-breaking further than
* necessary simplifies testing a bit.
*/
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(Node[] tab) {
TreeNode root = null;
for (TreeNode x = this, next; x != null; x = next) {
next = (TreeNode) x.next;
x.left = x.right = null;
if (root == null) {
x.parent = null;
x.red = false;
root = x;
} else {
K k = x.key;
int h = x.hash;
Class> kc = null;
for (TreeNode p = root; ; ) {
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
TreeNode 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);
}
/**
* Returns a list of non-TreeNodes replacing those linked from
* this node.
*/
final Node untreeify(HashMap map) {
Node hd = null, tl = null;
for (Node q = this; q != null; q = q.next) {
Node p = map.replacementNode(q, null);
if (tl == null)
hd = p;
else
tl.next = p;
tl = p;
}
return hd;
}
/**
* Tree version of putVal.
*/
final TreeNode putTreeVal(HashMap map, Node[] tab,
int h, K k, V v) {
Class> kc = null;
boolean searched = false;
TreeNode root = (parent != null) ? root() : this;
for (TreeNode p = root; ; ) {
int dir, ph;
K pk;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node xpn = xp.next;
TreeNode x = map.newTreeNode(h, k, v, xpn);
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode) xpn).prev = x;
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
/**
* 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 map, Node[] tab,
boolean movable) {
int n;
if (tab == null || (n = tab.length) == 0)
return;
int index = (n - 1) & hash;
TreeNode first = (TreeNode) tab[index], root = first, rl;
TreeNode succ = (TreeNode) next, pred = prev;
if (pred == null)
tab[index] = first = succ;
else
pred.next = succ;
if (succ != null)
succ.prev = pred;
if (first == null)
return;
if (root.parent != null)
root = root.root();
if (root == null || root.right == null ||
(rl = root.left) == null || rl.left == null) {
tab[index] = first.untreeify(map); // too small
return;
}
TreeNode p = this, pl = left, pr = right, replacement;
if (pl != null && pr != null) {
TreeNode s = pr, sl;
while ((sl = s.left) != null) // find successor
s = sl;
boolean c = s.red;
s.red = p.red;
p.red = c; // swap colors
TreeNode sr = s.right;
TreeNode pp = p.parent;
if (s == pr) { // p was s's direct parent
p.parent = s;
s.right = p;
} else {
TreeNode sp = s.parent;
if ((p.parent = sp) != null) {
if (s == sp.left)
sp.left = p;
else
sp.right = p;
}
if ((s.right = pr) != null)
pr.parent = s;
}
p.left = null;
if ((p.right = sr) != null)
sr.parent = p;
if ((s.left = pl) != null)
pl.parent = s;
if ((s.parent = pp) == null)
root = s;
else if (p == pp.left)
pp.left = s;
else
pp.right = s;
if (sr != null)
replacement = sr;
else
replacement = p;
} else if (pl != null)
replacement = pl;
else if (pr != null)
replacement = pr;
else
replacement = p;
if (replacement != p) {
TreeNode pp = replacement.parent = p.parent;
if (pp == null)
root = replacement;
else if (p == pp.left)
pp.left = replacement;
else
pp.right = replacement;
p.left = p.right = p.parent = null;
}
TreeNode r = p.red ? root : balanceDeletion(root, replacement);
if (replacement == p) { // detach
TreeNode pp = p.parent;
p.parent = null;
if (pp != null) {
if (p == pp.left)
pp.left = null;
else if (p == pp.right)
pp.right = null;
}
}
if (movable)
moveRootToFront(tab, r);
}
/**
* 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 map, Node[] tab, int index, int bit) {
TreeNode b = this;
// Relink into lo and hi lists, preserving order
TreeNode loHead = null, loTail = null;
TreeNode hiHead = null, hiTail = null;
int lc = 0, hc = 0;
for (TreeNode e = b, next; e != null; e = next) {
next = (TreeNode) e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
} else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
if (loHead != null) {
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {
tab[index] = loHead;
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
if (hiHead != null) {
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}
/* ------------------------------------------------------------ */
// Red-black tree methods, all adapted from CLR
static TreeNode rotateLeft(TreeNode root,
TreeNode p) {
TreeNode r, pp, rl;
if (p != null && (r = p.right) != null) {
if ((rl = p.right = r.left) != null)
rl.parent = p;
if ((pp = r.parent = p.parent) == null)
(root = r).red = false;
else if (pp.left == p)
pp.left = r;
else
pp.right = r;
r.left = p;
p.parent = r;
}
return root;
}
static TreeNode rotateRight(TreeNode root,
TreeNode p) {
TreeNode l, pp, lr;
if (p != null && (l = p.left) != null) {
if ((lr = p.left = l.right) != null)
lr.parent = p;
if ((pp = l.parent = p.parent) == null)
(root = l).red = false;
else if (pp.right == p)
pp.right = l;
else
pp.left = l;
l.right = p;
p.parent = l;
}
return root;
}
static TreeNode balanceInsertion(TreeNode root,
TreeNode x) {
x.red = true;
for (TreeNode xp, xpp, xppl, xppr; ; ) {
if ((xp = x.parent) == null) {
x.red = false;
return x;
} else if (!xp.red || (xpp = xp.parent) == null)
return root;
if (xp == (xppl = xpp.left)) {
if ((xppr = xpp.right) != null && xppr.red) {
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
} else {
if (x == xp.right) {
root = rotateLeft(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateRight(root, xpp);
}
}
}
} else {
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
} else {
if (x == xp.left) {
root = rotateRight(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateLeft(root, xpp);
}
}
}
}
}
}
static TreeNode balanceDeletion(TreeNode root,
TreeNode x) {
for (TreeNode xp, xpl, xpr; ; ) {
if (x == null || x == root)
return root;
else if ((xp = x.parent) == null) {
x.red = false;
return x;
} else if (x.red) {
x.red = false;
return root;
} else if ((xpl = xp.left) == x) {
if ((xpr = xp.right) != null && xpr.red) {
xpr.red = false;
xp.red = true;
root = rotateLeft(root, xp);
xpr = (xp = x.parent) == null ? null : xp.right;
}
if (xpr == null)
x = xp;
else {
TreeNode sl = xpr.left, sr = xpr.right;
if ((sr == null || !sr.red) &&
(sl == null || !sl.red)) {
xpr.red = true;
x = xp;
} else {
if (sr == null || !sr.red) {
if (sl != null)
sl.red = false;
xpr.red = true;
root = rotateRight(root, xpr);
xpr = (xp = x.parent) == null ?
null : xp.right;
}
if (xpr != null) {
xpr.red = (xp == null) ? false : xp.red;
if ((sr = xpr.right) != null)
sr.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateLeft(root, xp);
}
x = root;
}
}
} else { // symmetric
if (xpl != null && xpl.red) {
xpl.red = false;
xp.red = true;
root = rotateRight(root, xp);
xpl = (xp = x.parent) == null ? null : xp.left;
}
if (xpl == null)
x = xp;
else {
TreeNode sl = xpl.left, sr = xpl.right;
if ((sl == null || !sl.red) &&
(sr == null || !sr.red)) {
xpl.red = true;
x = xp;
} else {
if (sl == null || !sl.red) {
if (sr != null)
sr.red = false;
xpl.red = true;
root = rotateLeft(root, xpl);
xpl = (xp = x.parent) == null ?
null : xp.left;
}
if (xpl != null) {
xpl.red = (xp == null) ? false : xp.red;
if ((sl = xpl.left) != null)
sl.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateRight(root, xp);
}
x = root;
}
}
}
}
}
/**
* Recursive invariant check
*/
static boolean checkInvariants(TreeNode t) {
TreeNode tp = t.parent, tl = t.left, tr = t.right,
tb = t.prev, tn = (TreeNode) t.next;
if (tb != null && tb.next != t)
return false;
if (tn != null && tn.prev != t)
return false;
if (tp != null && t != tp.left && t != tp.right)
return false;
if (tl != null && (tl.parent != t || tl.hash > t.hash))
return false;
if (tr != null && (tr.parent != t || tr.hash < t.hash))
return false;
if (t.red && tl != null && tl.red && tr != null && tr.red)
return false;
if (tl != null && !checkInvariants(tl))
return false;
if (tr != null && !checkInvariants(tr))
return false;
return true;
}
}
}