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.Map.Entry;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
private static final long serialVersionUID = 362498820763181265L;
//HashMap默认初始化容量 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//HashMap的最大容量,若通过构造函数指定了更大的值,则使用该值
static final int MAXIMUM_CAPACITY = 1 << 30;
//HashMap默认的填充因子,当元素个数达到容量的0.75时触发rehash操作,对HashMap进行扩容
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* jdk 1.8之前的HashMap形象如下:
* key1 key2 key3 key4 key5 key6
* hashcode1 hashcode2 hashcode3 hashcode4 hashcode5 hashcode6
* ↓ ↓ ↓ ↓
* key7 key8 key9 key10
* ↓ ↓
* key11 key12
* ↓
* key13
* 横向是一个table,用于存放不同hashcode的K-V对
* 纵向是一个bucket(桶),用于存放相同hashcode的K-V对,实际上是一个链表
*/
//HashMap的数据结构由单链表转换为树的阀值,当单链表中节点数大于该值时会由链表转换为红黑树
static final int TREEIFY_THRESHOLD = 8;
//HashMap的数据结构由红黑树转换为单链表的阀值,当"桶中的"节点数小于该值时会由红黑树转换为链表
static final int UNTREEIFY_THRESHOLD = 6;
//HashMap中由链表转换为红黑树对应table的最小值,即只有当table元素数量达到该值时"桶"数据结构才有可能发生转换
static final int MIN_TREEIFY_CAPACITY = 64;
//HashMap的节点类,实现了Map的Entry接口,是一个单链表,是HashMap链式存储法对应的链表,用于处理Hash冲突
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;//节点对象对应的hash值
final K key;//保存key对象
V value;//保存value对象
Node<K,V> next;//指向下一个具有相同HashCode的节点的指针
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;
}
/*
*HashMap节点的比较,key与value值相同时才相等
*/
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 -------------- */
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* 若参数x是Comparable的实现类,则返回参数x的Class类型,否则返回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;
}
/**
* 仅当k与x的Class类型相同时,两者进行比较并返回比较结果,否则返回0
*/
@SuppressWarnings({"rawtypes","unchecked"})
static int compareComparables(Class<?> kc, Object k, Object x) {
//
return (x == null || x.getClass() != kc ? 0 :
((Comparable)k).compareTo(x));
}
//返回大于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;
}
/* ---------------- Fields -------------- */
//HashMap中存储元素的数组,长度总是为2的幂次倍
transient Node<K,V>[] table;
//存放具体元素的集合
transient Set<Map.Entry<K,V>> entrySet;
//HashMap中存放的元素个数,该值不等于table的长度
transient int size;
//记录HashMap数据结构改变的次数,用于迭代器触发快速失败策略
transient int modCount;
//记录HashMap下一次扩容阀值,超过该值则进行扩容threshold = capacity * load factor
int threshold;
//HashMap的填充因子,默认为0.75
final float loadFactor;
/* ---------------- Public operations -------------- */
//以指定的初始容量与填充因子构造一个HashMap
public HashMap(int initialCapacity, float loadFactor) {
//初始容量不可小于0,否则抛IllegalArgumentException
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
//若初始容量大于最大容量,则默认为最大容量
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//填充因子需>0且不可为非数字,否则抛IllegalArgumentException
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
//以指定的初始容量构造一个HashMap
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/*
* 以默认属性构造一个HashMap
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
//以指定Map中的元素构造一个HashMap
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
//将m中的所有元素添加到HashMap中
putMapEntries(m, false);
}
//将m中的所有元素添加到HashMap中,当构造HashMap时候调用,evict为false,其余时候为true
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
//若HashMap的table未初始化(即构造时候调用该方法),则根据m的元素个数,计算要创建的HashMap的容量
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);
}
//若HashMap已初始化(即非构造时候调用该方法),m的元素个数大于HashMap的扩容阀值,则对HashMap进行扩容
else if (s > threshold)
resize();//该方法十分耗时,需尽量避免HashMap发生扩容
//遍历m的所有元素,放入HashMap中
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);
}
}
}
//返回HashMap的元素个数
public int size() {
return size;
}
//判断HashMap的是否为空
public boolean isEmpty() {
return size == 0;
}
//返回指定key映射的value对象,若不存在则返回null
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//根据key获取HashMap中对应的节点对象
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值计算在table中对应的下标位置并取得第一个节点,若第一个节点的key
* 与指定key相同,则直接返回第一个节点
*/
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//若第一个节点不匹配,且存在后续节点
if ((e = first.next) != null) {
//若该节点是红黑树类型
if (first instanceof TreeNode)
//则按照红黑树方式取到指定节点并返回
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//若是单链表类型节点,则遍历单链表,找到key与指定key相等的便返回
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
//若table,即HashMap中无元素,则返回null
return null;
}
/*
*判断HashMap中是否指定key
*/
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
/**
* 将k-v对放入HashMap中,若HashMap中已存在相同key,则老的value会被覆盖
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
*将k-v对放入HashMap中,当onlyIfAbsent = true时,key相同时不覆盖已存在的值(putIfAbsent方法,key存在时不覆盖),
*evict只有在HashMap创建时候为false,表示进入创建模式,其余时候为true
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//当table为null或者table中无元素时,调用resize方法初始化table
if ((tab = table) == null || (n = tab.length) == 0)
//此时n保存的是新table的容量值
n = (tab = resize()).length;
//计算当前k-v对在table中的下标位置,并判断当前
//下标位置是否已经被其他k-v对占用,若没被占用则
//直接new节点放入该位置
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
//若当前下标位置已被其他k-v对占用,则分3种情况来处理
Node<K,V> e; K k;
//若老的k-v对的hash值与当前k-v对的hash值相等,且key也是相等的,直接覆盖value
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//则用e保存老的k-v对
e = p;
//若老的k-v对是红黑树节点,则按红黑树节点进行添加
else if (p instanceof TreeNode)
//用e保存老的红黑树节点
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//若不属于上面2种情况,即当前位置存放的是一个单链表,遍历单链表
for (int binCount = 0; ; ++binCount) {
//若遍历到单链表最后一个节点,直接new节点放入单链表尾部
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//若该单链表长度大于等于"链表转树的阈值",则将单链表转换为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//跟上面第1种情况一样,在单链表中的节点,若hash值相等且key也相等,直接覆盖value
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//上面只是找到要进行覆盖的k-v节点,这里才对value值进行覆盖
if (e != null) {
//保存老的value值
V oldValue = e.value;
//上面说了,只有当onlyIfAbsent为true时,不覆盖老的value,
//onlyIfAbsent为false时
if (!onlyIfAbsent || oldValue == null)
//覆盖老的value
e.value = value;
afterNodeAccess(e);
//返回老的value
return oldValue;
}
}
//结构改变次数递增
++modCount;
//若HashMap中的元素个数大于扩容阈值,则进行扩容
/*
* 这里就可能会产生一个内存浪费的问题,当我们put到HashMap中的k-v对的hash值经常出现重复的,
* 即会出现这么一种情况,table中并没有放足够的元素,而由于hash相同,就会导致单链表or红黑树
* 过大,而此时table中有可能也就少数个位置有元素,而其他位置是空着的,这是HashMap发生扩容,便
* 会导致越来越多的table位置是空着的,浪费内存
* 想象这么一个极端情况:不断往HashMap中put进去key不同而hash值相同的k-v对,这时所有的k-v对
* 都会在table的同一个位置上,形成单链表or红黑树,而table的其他位置是空着的,HashMap发生扩容
* 便会翻倍地增加table上的空闲位置
*/
if (++size > threshold)
resize();
afterNodeInsertion(evict);
//没有覆盖老的value,返回null
return null;
}
/**
* 对HashMap进行扩容的方法,初始化HashMap或者以 原容量*2 的方式进行扩容,
* 最后返回扩容后的table
*/
final Node<K,V>[] resize() {
//这里开始依据现有HashMap的容量与扩容阈值来确定新的容量与扩容阈值
Node<K,V>[] oldTab = table;
//取得原table中元素的数量与扩容阈值,当这两个值大于0时,表示HashMap已经初始化过,
//新table容量在原基础上*2即可
int oldCap = (oldTab == null) ? 0 : oldTab.length;//保存原table大小
//保存原扩容阈值
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
//若原table中元素数量已达到最大值,无法扩容,直接返回
//这种情况会造成单链表的长度过大,效率下降
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//若扩容后的容量不会大于等于最大值,则新table容量与新扩容阈值在原table的基础上翻倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1;
}
//这种情况发生在使用指定初始化容量or填充因子初始化HashMap时,扩容阈值会被初始化
else if (oldThr > 0)
//将原扩容阈值作为新容量
newCap = oldThr;
else {
//最后这种情况表示HashMap未被初始化过,使用默认值来进行初始化
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//若新扩容阈值为0(上面流程进入else if代码块)
if (newThr == 0) {
//重新计算新扩容阈值,最大不超过MAXIMUM_CAPACITY
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//更新该HashMap的扩容阈值
threshold = newThr;
//这里开始初始化新table,将原tabke中的元素放入扩容后的新table中
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
//更新该HashMap中的table
table = newTab;
//将原table中的元素逐一放入新table中
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//若节点不为null
if ((e = oldTab[j]) != null) {
oldTab[j] = null;//主动释放原table的空间
//若该节点的单链表中只有一个节点,没有后续节点,则直接重新计算在新table中的index,并将此节点存储到新table对应的index位置
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
//若节点是红黑树节点,则按红黑树方式进行移动
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { //若该节点的单链表中不止一个节点,则迁移单链表中的每一个节点
/*
* 在这里将单链表中的k-v对按hash值分成lo与hi两种类型,lo类型的k-v对在新table中的位置与在原table中相同,hi类型
* 的k-v对在新table中的位置是在"原table位置+oldCap(下面解释与代码可知)",这么分类主要是将单链表中冲突的节点分
* 散到新table中,提高效率,而k-v对属于何种类型则取决于"(e.hash & oldCap) == 0"这一条件,为何如此这一设计呢?
* 我们都知道,HashMap的容量皆是2的幂,二进制形式就是100..00这种,而我们知道长度为n的数组,下标最大也就是 n-1,即2的
* 幂减1,二进制形式就是1111..111这种,而k-v对在table中的下标位置计算公式是 "e.hash & (capacity - 1)",而二进
* 制 &操作 是只有同位上的值皆是1算出来才是1的,如:6 & 3 = 2,二进制&如下
* 110
* &011 = 010
* 因此,若上面的判定条件为true,则意味着oldCap为1的那位对应的k-v对的hash位的为0(因oldCap除了最高位为1,其余为0),
* 对新下标的计算没有影响(懵逼?等下看例子就懂),而从上面代码可知,新table下标位的计算是"e.hash & (newCap - 1)",
* 且newCap = oldCap << 2(oldCap * 2),即"新下标 = e.hash & ((oldCap << 2) - 1)",若上面的判定条件为false,
* 则oldCap为1的那位对应的k-v对的hash位为1,新下标就相当于多了10..00,就是oldCap(还是很懵逼吧?直接上例子)
* 如:oldCap = 16,则newCap = 32,16二进制为10000,32二进制为100000,(oldCap-1)二进制为1111,(newCap-1)二进制
* 为11111,判定"(e.hash & oldCap) == 0"的时候如下:
* hash: xxxx xxxx xxxy xxxx
* &oldCap: 0000 0000 0001 0000
* 若条件为true,则y = 0,若条件为false,则y = 1
* 计算old下标时候如下:
* hash: xxxx xxxx xxxy xxxx
* &(oldCap-1): 0000 0000 0000 1111 (ps:old下标计算与y无关,只是为下面做铺垫)
* 计算new下标时候如下:
* hash: xxxx xxxx xxxy xxxx
* &(newCap-1): 0000 0000 0001 1111
* 此时,当y=0时,old与new计算出来的下标都是"0xxxx&01111",对新下标没影响;而当y=1时,新下标就是"1xxxx&11111",
* 这个时候新下标就相当于多了10..00,因为1xxxx&11111 = 1xxxx&01111 + 10000,用具体数值计算如下:
* y=0时:
* hash:0000 1101
* &oCap:0000 1111 = 0000 1101
* hash:0000 1101
* &nCap:0001 1111 = 0000 1101
* y=1时:
* hash:0001 1101
* &oCap:0000 1111 = 0000 1101
* hash:0001 1101
* &nCap:0001 1111 = 0001 1101
* new下标 = old下标 + 10000
* 0000 1101
* +0001 0000 = 0001 1101
* 这下懂为什么hi类型的k-v对在新table的位置是"原table位置 + oldCap"了吧!
* 这个设计贼特么巧妙,省去了重新计算hash值的时间,而且把之前有冲突的k-v对均匀分散到新table中了
* http://www.importnew.com/20386.html
* https://www.zhihu.com/question/28365219 参考的
*/
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
//构造lo类型k-v对新的单链表
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
//构造hi类型k-v对新的单链表
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
//lo类型的k-v对在新table的位置与原table相同
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
//hi类型的k-v对在新table的位置为"原table位置 + oldCap"
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
//返回新的table
return newTab;
}
/*
* 将单链表数据结构转换为红黑树
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//若table为初始化或table容量小于MIN_TREEIFY_CAPACITY
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
//则用resize进行初始化or扩容
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
//这里开始将单链表结构转换为红黑树
TreeNode<K,V> hd = null, tl = null;
do {
//将单链表节点转换为红黑树节点并返回
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);
//上面的do-while只是将红黑树每个节点的位置进行前后关联(可以理解成是一条以红
//黑树节点为节点的双向链表),并没有转换为树结构,这里才是转换成树结构
if ((tab[index] = hd) != null)
//将链表结构转换为红黑树
hd.treeify(tab);
}
}
/**
* 将指定Map中的k-v对放入当前HashMap中,若当前HashMap中存在key相同的,则老的value会被覆盖
*/
public void putAll(Map<? extends K, ? extends V> m) {
putMapEntries(m, true);
}
/**
* 移除HashMap中指定key的节点
*/
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
/**
* value是按值移除节点时候用到
* matchValue为true时,只有value相等时候才移除,为false时,按key移除
* movable为false时,移除节点过程中不移动其他节点,为true时则移动其他节点
*
*/
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;
//若table不为null,且table元素个数大于0与key对应下标位置存在节点时,才进行remove
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;
//这里开始取得要remove的节点并存放到node上,分3种情况
//1.该下标位置的第一个节点就是要remove的节点,不分是Node节点还是TreeNode节点(hash值相等,key也相等)
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
//该下标位置的第一个节点不是要remove的节点,则判断是红黑树还是单链表结构
else if ((e = p.next) != null) {
//2.若是红黑树,则调用红黑树的方法取得要remove的节点
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
//3.若是单链表,则遍历单链表取得要remove的节点(hash值相等,key也相等)
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//这里根据参数决定按key移除or按value移除,按value移除当且仅当matchValue = true且value相等时才移除
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
//若节点是红黑树节点(第1种情况且是红黑树节点,或是第二种情况),则调用红黑树的方法移除节点
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
//若要remove的节点属于第1种情况且不是红黑树节点,则直接将第2个节点放入table指定位置上(即将第2个节点上移取代原本第1个节点的位置)
else if (node == p)
tab[index] = node.next;
//若要remove的节点属于第3种情况,即单链表,直接将next指针指向要remove节点的next节点即可
else
p.next = node.next;
//结构改变次数+1
++modCount;
//HahsMap元素个数-1
--size;
afterNodeRemoval(node);
//返回已移除的节点
return node;
}
}
return null;
}
/**
* 移除HashMap中所有的k-v对,该方法执行后HashMap将变为empty(空,不是null)
*/
public void clear() {
Node<K,V>[] tab;
//结构改变次数+1
modCount++;
//若HashMap中有元素
if ((tab = table) != null && size > 0) {
//HashMap元素个数置为0
size = 0;
//遍历table并将各个位置上的元素置为null
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}
/**
* 判断HashMap中是否有key对应指定的value,有对应则返回true,否则返回false
*/
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
//从头开始遍历table上的每一个位置
for (int i = 0; i < tab.length; ++i) {
//遍历table每一个位置上的单链表or红黑树结构
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
//若value值相等,则返回true
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}
/**
* 返回一个包含Map中所有key的Set集合,对Map进行的改变也会映射到这个Set中,
* 当返回的Set在进行迭代的时候,Map发生改变,则迭代的结果是不确定的(除非是调用
* 迭代器自己的remove操作而发生的改变,该Set支持一系列remove操作,但不支持
* add操作),KeySet是在第一次调用的时候创建,并响应后续的请求,因为不是同步执行
* 的,所以在多次调用可能返回的集合不是同一个,KeySet的具体创建在HashMap的父类
* AbstractMap中
*/
public Set<K> keySet() {
Set<K> ks;
return (ks = keySet) == null ? (keySet = new KeySet()) : ks;
}
/**
* 摘自父类AbstractMap,实际上就是以匿名内部类的方式实现AbstractSet中的抽象
* 方法,而该Set集合的元素是从EntrySet中取得的(即依赖于EntrySet,至于EntrySet
* 是怎么实现的,下面会介绍到)
*/
public Set<K> keySet() {
if (keySet == null) {
//直接new一个AbstractSet
keySet = new AbstractSet<K>() {
public Iterator<K> iterator() {
return new Iterator<K>() {
//迭代器Iterator取得是EntrySet中的迭代器
private Iterator<Entry<K,V>> i = entrySet().iterator();
public boolean hasNext() {
return i.hasNext();
}
//next方法取得是EntrySet中的Entry的key
public K next() {
return i.next().getKey();
}
public void remove() {
i.remove();
}
};
}
//size方法实际上调用的也是EntrySet的size方法
public int size() {
return AbstractMap.this.size();
}
//isEmpty方法实际上就是调用EntrySet的size方法,判断返回值是否==0
public boolean isEmpty() {
return AbstractMap.this.isEmpty();
}
//clear方法也是调用EntrySet的clear方法
public void clear() {
AbstractMap.this.clear();
}
//contains方法实现如下,也是依赖EntrySet实现的
public boolean contains(Object k) {
return AbstractMap.this.containsKey(k);
}
//也是摘自父类AbstractMap
public boolean containsKey(Object key) {
//取得EntrySet的迭代器
Iterator<Map.Entry<K,V>> i = entrySet().iterator();
//若key==null,直接迭代,若遇到key==null的返回true
if (key==null) {
while (i.hasNext()) {
Entry<K,V> e = i.next();
if (e.getKey()==null)
return true;
}
} else {
//若key!=null,迭代并使用key的equal方法判断是否相等,是则返回true
while (i.hasNext()) {
Entry<K,V> e = i.next();
if (key.equals(e.getKey()))
return true;
}
}
return false;
}
};
}
return keySet;
}
//KeySet的实现类,没什么特殊的,其中的Spliterator与forEach在List源码那里有简单介绍
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();
}
}
}
/**
* 返回一个包含Map中所有value的Collection集合,对Map进行的改变也会映射到这个Collection
* 中,当返回的Set在进行迭代的时候,Map发生改变,则迭代的结果是不确定的(除非是调用
* 迭代器自己的remove操作而发生的改变,该Collection支持一系列remove操作,但不支持
* add操作),与KeySet类似
*/
public Collection<V> values() {
Collection<V> vs;
return (vs = values) == null ? (values = new Values()) : vs;
}
/*
* 摘自父类AbstractMap,与KeySet一样,依赖于EntrySet,KeySet取的是EntrySet的key,
* Values取的是EntrySet的value
*/
public Collection<V> values() {
if (values == null) {
values = new AbstractCollection<V>() {
public Iterator<V> iterator() {
return new Iterator<V>() {
private Iterator<Entry<K,V>> i = entrySet().iterator();
public boolean hasNext() {
return i.hasNext();
}
public V next() {
return i.next().getValue();
}
public void remove() {
i.remove();
}
};
}
public int size() {
return AbstractMap.this.size();
}
public boolean isEmpty() {
return AbstractMap.this.isEmpty();
}
public void clear() {
AbstractMap.this.clear();
}
public boolean contains(Object v) {
return AbstractMap.this.containsValue(v);
}
};
}
return values;
}
//跟KeySet类似,不做介绍
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();
}
}
}
/**
* 跟之前的KeySet与values一样,返回一个HashMap的k-v的映射,对Map进行的改变也会
* 映射到这个EntrySet中,当返回的EntrySet在进行迭代的时候,Map发生改变,则迭代的
* 结果是不确定的(除非是调用迭代器自己的remove操作而发生的改变,该EntrySet支持一
* 系列remove操作,但不支持add操作)
*/
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
//在HashMap中实际上就是Node节点的集合
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
//返回Entry的迭代器,具体怎么实现的,下面会介绍
public final Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
//判断指定对象(需是Entry类型)是否在EntrySet集合里面
public final boolean contains(Object o) {
//不是Entry类型,直接返回false
if (!(o instanceof Map.Entry))
return false;
//强转成Entry类型
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
//取得key
Object key = e.getKey();
//根据key到HashMap中取得对应的节点
Node<K,V> candidate = getNode(hash(key), key);
//取得到对应节点且key与value相等才算是包含在HasMap中
return candidate != null && candidate.equals(e);
}
//移除指定对象(需是Entry类型)
public final boolean remove(Object o) {
if (o instanceof Map.Entry) {
//强转成Entry
Map.Entry<?,?> e = (Map.Entry<?,?>) o;
//取得key
Object key = e.getKey();
//取得value
Object value = e.getValue();
//根据key与value移除对应的Node节点
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
/*
* 根据key获取对应的value,若无对应的value,则返回参数中的defaultValue
*/
@Override
public V getOrDefault(Object key, V defaultValue) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}
/*
* 若HashMap中不存在,则将k-v对放进去
*/
@Override
public V putIfAbsent(K key, V value) {
return putVal(hash(key), key, value, true, true);
}
/*
* 根据k-v对移除指定HashMap节点,只有key与value完全相等时才移除
*/
@Override
public boolean remove(Object key, Object value) {
return removeNode(hash(key), key, value, true, true) != null;
}
/*
* 将指定key的节点的value替换为newValue,只有当节点的value与oldValue相等时才替换
*/
@Override
public boolean replace(K key, V oldValue, V newValue) {
Node<K,V> e; V v;
//取得对应的节点且value与oldValue相等时才执行替换
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;
}
/*
* 将指定key的节点的value替换为newValue
*/
@Override
public V replace(K key, V value) {
Node<K,V> e;
//取得对应的节点并替换value
if ((e = getNode(hash(key), key)) != null) {
V oldValue = e.value;
e.value = value;
afterNodeAccess(e);
return oldValue;
}
return null;
}
/*
* 该方法是jdk1.8新增的方法,可以构建本地缓存,降低程序的计算量,程序的复杂度,使代码简洁,易懂
* 大致流程就是,首先判断缓存MAP中是否存在指定key的值,如果存在,则返回节点的值;如果不存在,会
* 自动调用mappingFunction(key)计算key对应的value,然后将key-value对放入到缓存Map,
* java8会使用thread-safe的方式从cache中存取记录
*/
@Override
public V computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) {
if (mappingFunction == null)
throw new NullPointerException();
//根据key计算Hash值
int hash = hash(key);
Node<K,V>[] tab; Node<K,V> first; int n, i;
//该变量用于记录key对应的table位置上节点的个数,超过链表转换树的阈值时会将单链表转换为红黑树
int binCount = 0;
TreeNode<K,V> t = null;
Node<K,V> old = null;
//若当前HashMap的size超过扩容阈值或者未初始化,则调用resize方法扩容或初始化
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
//根据hash值计算key对应的节点在table中的位置,并取得该位置的第一个节点
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 {
//则遍历单链表取得对应的节点,仅当hash相等且key相等才是所需节点
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
//若取得到节点且节点的value不为null,则直接返回节点的value
V oldValue;
if (old != null && (oldValue = old.value) != null) {
afterNodeAccess(old);
return oldValue;
}
}
//若取不到节点,则调用Function对象的apply方法计算出key对应的value值
V v = mappingFunction.apply(key);
if (v == null) {
//若计算出的value值为null,直接返回null
return null;
} else if (old != null) {
//这种情况是key原本在HashMap中有对应的节点,但节点的value为
//null,则把计算出来的value作为key对应节点的value后返回
old.value = v;
afterNodeAccess(old);
return v;
}
else if (t != null)
//这种情况是key原本在HashMap中无对应节点,且key对
//应的位置是一颗红黑树,则将计算结果放入红黑树中
t.putTreeVal(this, tab, hash, key, v);
else {
//这种情况是key原本在HashMap中无对应节点,且key对
//应的位置是单链表,直接创建单链表节点
tab[i] = newNode(hash, key, v, first);
//若binCount超过单链表转换树的阈值(大于8),则将单链表转换为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
}
//结构修改次数+1
++modCount;
//HashMap元素个数+1
++size;
afterNodeInsertion(true);
//返回新计算出来的value
return v;
}
/*
* 若HashMap中存在指定key,则根据key计算出value并替换掉老的value,最后返回计算出来的value
*/
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;
//计算key的hash值
int hash = hash(key);
//根据key与hash值取得节点
if ((e = getNode(hash, key)) != null &&
(oldValue = e.value) != null) {
//根据key与老的value计算新的value
V v = remappingFunction.apply(key, oldValue);
//若计算出来的value不为null
if (v != null) {
//则替换老的value
e.value = v;
afterNodeAccess(e);
//返回计算出来的value
return v;
}
else
//若计算出来的value为null,则移除该节点
removeNode(hash, key, null, false, true);
}
return null;
}
//根据key与oldValue计算出节点的新value值
@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;
//该变量用于记录key对应的table位置上节点的个数,超过链表转换树的阈值时会将单链表转换为红黑树
int binCount = 0;
TreeNode<K,V> t = null;
Node<K,V> old = null;
//若当前HashMap元素个数超过扩容阈值或为初始化,则调用resize方法扩容或初始化
if (size > threshold || (tab = table) == null ||
(n = tab.length) == 0)
n = (tab = resize()).length;
//根据hash值计算key对应的节点在table中的位置,并取得该位置的第一个节点
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 {
//则遍历单链表取得对应的节点,仅当hash相等且key相等才是所需节点
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
old = e;
break;
}
++binCount;
} while ((e = e.next) != null);
}
}
//取出key对应节点老的value
V oldValue = (old == null) ? null : old.value;
//根据key与oldValue计算新的value
V v = remappingFunction.apply(key, oldValue);
if (old != null) {
//若key对应的节点存在且计算出来的value不为null,则节点的value替换为计算出来的value
if (v != null) {
old.value = v;
afterNodeAccess(old);
}
else
//若key对应的节点存在且计算出来的value为null,则移除该节点
removeNode(hash, key, null, false, true);
}
else if (v != null) {
//若key对应的节点不存在且对应位置是一颗红黑树
if (t != null)
//则将key与计算出来的value作为红黑树的节点放进去
t.putTreeVal(this, tab, hash, key, v);
else {
//若key对应的节点不存在且对应位置是单链表,则将key与计算出来的value作为
//单链表的节点放进去
tab[i] = newNode(hash, key, v, first);
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash);
}
//结构改变次数+1
++modCount;
//HashMap元素个数+1
++size;
afterNodeInsertion(true);
}
//返回计算出来的value
return v;
}
/*
* 该方法与上面的类似,只是当计算出来的value为null时多了参数value这一操作,不多做叙述
*/
@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();
}
}
/*
* 使用function计算出来的value替换当前HashMap中所有key对应的value
*/
@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);
}
}
//在进行replaceAll过程中,别的地方对HashMap进行结构上的操作会导致ConcurrentModificationException
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
/* ------------------------------------------------------------ */
// Cloning and serialization
/*
*返回当前HashMap的一个浅复制
*/
@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;
}
//返回当前HashMap的填充因子
final float loadFactor() { return loadFactor; }
//返回当前HashMap的容量
final int capacity() {
return (table != null) ? table.length :
(threshold > 0) ? threshold :
DEFAULT_INITIAL_CAPACITY;
}
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);
}
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
//HashMap的抽象迭代器,是实现KeyIterator、ValueIterator、EntryIterator的基础
abstract class HashIterator {
//下一个节点的指针
Node<K,V> next; // next entry to return
//当前节点的指针
Node<K,V> current; // current entry
//记录当前结构的改变次数,用于触发快速失败机制ConcurrentModificationException
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) { // 将next指针前进到table中第一个不为null的节点
do {} while (index < t.length && (next = t[index++]) == null);
}
}
//介绍略
public final boolean hasNext() {
return next != null;
}
//迭代取得节点,并使next指向其他节点
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
//迭代过程中使用非迭代器方法造成HashMap结构次数改变则触发快速失败机制,抛ConcurrentModificationException
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
//next = (current = e).next == null表示只有当table的index位置上有且仅有一个节点
//的时候,index才会向后移动递增,若table的index位置上存在单链表or红黑树(有hash冲突),这时
//候next指针会指向单链表or红黑树的下一个节点
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();
//跟上面一样,触发了快速失败机制,抛ConcurrentModificationException
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
K key = p.key;
//从HashMap中移除该节点
removeNode(hash(key), key, null, false, false);
//expectedModCount重新赋值,便不会触发快速失败机制,抛ConcurrentModificationException,
//迭代器remove之所以不会快速失败就是因为有同步结构改变次数到迭代器中,而迭代器之外的结构次数改
//变没同步到迭代器中
expectedModCount = modCount;
}
}
//HashMap的key的迭代器
final class KeyIterator extends HashIterator
implements Iterator<K> {
public final K next() { return nextNode().key; }
}
//HashMap的value的迭代器
final class ValueIterator extends HashIterator
implements Iterator<V> {
public final V next() { return nextNode().value; }
}
//HashMap的Entry的迭代器
final class EntryIterator extends HashIterator
implements Iterator<Map.Entry<K,V>> {
public final Map.Entry<K,V> next() { return nextNode(); }
}
/* ------------------------------------------------------------ */
// spliterators
//HashMap的可分割迭代器,阿西吧,这个暂时先跳过,以后需要用到再研究,可参考ArrayList与LinkedList中的
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;
}
}
//同HashMapSpliterator
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;
}
}
//同HashMapSpliterator
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);
}
}
//同HashMapSpliterator
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
// Create a regular (non-tree) node
Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
return new Node<>(hash, key, value, next);
}
// For conversion from TreeNodes to plain nodes
Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
return new Node<>(p.hash, p.key, p.value, next);
}
// Create a tree bin node
TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
return new TreeNode<>(hash, key, value, next);
}
// For treeifyBin
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}
/**
* Reset to initial default state. Called by clone and readObject.
*/
void reinitialize() {
table = null;
entrySet = null;
keySet = null;
values = null;
modCount = 0;
threshold = 0;
size = 0;
}
// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }
// Called only from writeObject, to ensure compatible ordering.
void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
Node<K,V>[] tab;
if (size > 0 && (tab = table) != null) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> 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<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
/**
* 返回红黑树的根节点
*/
final TreeNode<K,V> root() {
//往上遍历红黑树
for (TreeNode<K,V> r = this, p;;) {
//根节点没有parent节点
if ((p = r.parent) == null)
return r;
r = p;
}
}
/**
* 确保给定的根节点是红黑树的第一个节点
*/
static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
int n;
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;
tab[index] = root;
TreeNode<K,V> rp = root.prev;
if ((rn = root.next) != null)
((TreeNode<K,V>)rn).prev = rp;
if (rp != null)
rp.next = rn;
if (first != null)
first.prev = root;
root.next = first;
root.prev = null;
}
assert checkInvariants(root);
}
}
/**
* 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<K,V> find(int h, Object k, Class<?> kc) {
TreeNode<K,V> p = this;
do {
int ph, dir; K pk;
TreeNode<K,V> pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if (pl == null)
p = pr;
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
p = (dir < 0) ? pl : pr;
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}
/**
* Calls find for root node.
*/
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
/**
*当两个对象无法通过比较器进行大小比较时,该方法会先通过类名比较,
*若类名比较不成功(即结果为0)时,则调用系统的本地方法生成hashCode
*进行比较并返回最终比较结果
*/
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<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;
//从根节点开始遍历红黑树,确定当前节点在红黑树中的位置
for (TreeNode<K,V> p = root;;) {
int dir;//存放当前节点与红黑树其他节点的比较结果,小于存1,小于存-1,等于存0
int ph;
K pk = p.key;
//若当前节点hash值小于节点p的hash值
if ((ph = p.hash) > h)
dir = -1;
//若当前节点hash值大于节点p的hash值
else if (ph < h)
dir = 1;
//若不能根据hash值来比较,即hash值相等
else if ((kc == null &&
//取得当前节点key的比较器类型
(kc = comparableClassFor(k)) == null) ||
//比较当前节点key与p的key的大小(大于返回1,小于返回-1,其余返回0)
(dir = compareComparables(kc, k, pk)) == 0)
//若else if中比较结果还是为0,即无法比较,则使用tieBreakOrder方法进行比较并返回最终结果
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
//若节点p的左节点有位置且dir<=0,则放到节点p的左节点,
//若节点p的右节点有位置且dir>0,则放到节点p的右节点,否
//则遍历下一个节点重复比较,直到有存在满足条件的位置
if ((p = (dir <= 0) ? p.left : p.right) == null) {
//设置x的parent节点
x.parent = xp;
//dir<=0,放到左节点
if (dir <= 0)
xp.left = x;
//dir>0,放到右节点
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<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;
}
}
}
}
}
/**
* Recursive invariant check
*/
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)
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;
}
}
}
关于红黑树部分上面源码没介绍到,先占个坑,后续补上