前情提要
TREEIFY_THRESHOLD(链表转化为红黑树的阈值)
见 MIN_TREEIFY_CAPACITY。
static final int TREEIFY_THRESHOLD = 8;
UNTREEIFY_THRESHOLD(红黑树转化为链表的阈值)
见 split(HashMap map, Node[] tab, int index, int bit)。
static final int UNTREEIFY_THRESHOLD = 6;
MIN_TREEIFY_CAPACITY(最小的链表转化为红黑树的容量)
将键值映射放入 table 数组中后,如果键值映射的数量大于等于 TREEIFY_THRESHOLD 且 table 数组的长度大于等于 MIN_TREEIFY_CAPACITY,链表转化为红黑树。
static final int MIN_TREEIFY_CAPACITY = 64;
Node
可以认为就是 Java 7 HashMap 中的 Entry,在它的 equals 方法中,如果参数 o 和它是相同的引用,或参数 o 是 Map.Entry 类型的实例且参数 o 的 key 和 value 域和它的相同,返回 true,否则返回 false。
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
...
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
hash(Object key)
参数 key 为空时也返回 0,不为空时返回它的哈希与它的哈希右移 16 位的异或结果。因为引入了红黑树,所以哈希函数不需要那么复杂了。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
tableSizeFor(int cap)
返回刚好大于等于 cap 的 2 的幂。
static final int tableSizeFor(int cap) {
// 避免当 cap 本来就是 2 的幂时返回 cap * 2
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
/*
构造方法保证 cap >= 0,则 n >= -1,
如果 n 初始化为 01xxxxxx xxxxxxxx xxxxxxxx xxxxxxxx,
经过以上五个或操作后变为 01111111 11111111 11111111 11111111(1 << 31 - 1),
此时 n 大于 MAXIMUM_CAPACITY,返回 MAXIMUM_CAPACITY;
如果 n 初始化为 11111111 11111111 11111111 11111111(-1),
经过以上五个或操作后变为 11111111 11111111 11111111 11111111(-(1 << 31)).
此时 n 小于 0,返回 1;其他情况返回 n + 1。
*/
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
table
默认值为 null,不再为 EMPTY_TABLE 了,当时就感觉没什么意义。
transient Node<K,V>[] table;
HashMap(int initialCapacity, float loadFactor)
先校验参数,再给 loadFactor 和 threshold 域赋值。在构造函数中就把 table 数组的长度确定好了,不用再等到初始化 table 数组时再确定。
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);
}
HashMap()
其实 HashMap(int initialCapacity, float loadFactor) 做的事情就是给 loadFactor 和 threshold 域赋值,所以没必要再调用它了,省去了校验的麻烦,threshold 域没被赋值也无所谓,resize() 会对其进行处理。
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
HashMap(Map m)
初始化 loadFactor 域,调用 putMapEntries 方法。
在 putMapEntries 方法中,当参数 m 的键值映射的数量大于 0 时,如果 table 数组为空,根据参数 m 的键值映射的数量给 threshold 赋值;如果参数 m 的键值映射的数量大于 threshold,调整大小。最后遍历参数 m 中的 Entry 对象,调用 putVal 方法将它们放入 table 数组中,调用 putVal 方法时如果 table 数组没有初始化则初始化。
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
/*
被构造方法调用时,假设 s == 12,如果没有 + 1.0F,则 ft = 16,t = 16,
t > threhold == 0,threhold = 16,下次添加元素时会扩容,
但如果不再添加元素,能节省一半的空间;有 + 1.0F,则 threhold = 32,
下次添加元素时不会扩容,但如果不再添加元素,会浪费一半的空间。
*/
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);
}
}
}
get(Object key)
调用 getNode 方法。
在 getNode 方法中,先检查第一个节点,再检查第一个节点的下一个节点,根据节点的类型选择不同的查找方式。
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
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);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
put(K key, V value)
调用 putVal 方法。
在 putVal 方法中,如果 table 数组为空或长度为 0,初始化 table 数组。如果 table 数组中对应的位置为空,初始化 table 数组中对应的位置;如果不为空,寻找域 key 和 value 与参数相同的 Node 对象,找到了就替换 value 域的值,找不到就根据节点的类型将其放入 table 数组中,当节点是链表节点时要考虑转换为红黑树的情况,最后考虑是否需要进行扩容。返回值为被替换的 value 域的值。
public V put(K key, V value) {
return putVal(hash(key), key, value, 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;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 与 JDK 7 不同,后扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
resize()
先将旧容量、旧阈值、新容量、新阈值赋值,一般情况下,新容量为旧容量的两倍,新阈值为旧阈值的两倍,然后将旧数组中的节点转移到新数组中,如果一个位置上只有一个节点,直接转移,否则,根据结点的类型,根据节点哈希和旧容量逻辑与的结果,将节点放在新数组的低位或高位上,低位和高位相差一个旧数组容量,最后返回新数组。
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
// 如果旧容量大于等于最大容量
if (oldCap >= MAXIMUM_CAPACITY) {
// 将阈值设置为 Integer 的最大值(以后不会再触发扩容)
threshold = Integer.MAX_VALUE;
// 返回旧表
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// 表未初始化时
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
/*
将树中的节点拆分为较低和较高的树,
节点在较低索引还是较高索引(较低索引 + 旧表长度)的红黑树上取决于它的哈希值和旧表长度的与操作的结果
如果拆分后树太小(大小小于等于 UNTREEIFY_THRESHOLD),则将树变为链表。
仅从 resize 调用;请参阅上面关于拆分位和索引的讨论。
*/
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
// 节点在较低索引还是较高索引(较低索引 + 旧表长度)的链表上取决于它的哈希值和旧表长度的与操作的结果
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
treeifyBin(Node[] tab, int hash)
如果 table 数组没有被初始化,初始化 table 数组;如果 table 数组的长度小于 MIN_TREEIFY_CAPACITY,调整 table 数组的大小为原来的两倍;如果 table 数组中的对应位置不为空,将链表转换为红黑树,同时维护一个双向链表。removeTreeNode 和 containsValue 方法中用到了双向链表。
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
remove(Object key)
调用 removeNode 方法。
在 removeNode 方法中,先获得移除的节点,再根据节点的类型(树节点、链表头节点、链表其它节点)选择不同的方式移除节点。
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
/*
matchValue 当 remove 方法与 value 有关时为 true
movable 仅在抽象类 HashIterator 的 remove 方法对 removeNode 的调用中为 false
*/
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
containsValue(Object value)
TreeNode 是 Node 的子类,继承了 Node 的 next 域。链表转换为红黑树后,像 containsValue 方法这种需要遍历所有节点的方法仍使用 next 域。
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}