在上篇文章《HashMap、ConcurrentHashMap简单原理讲解》中,简单说了下HashMap的底层数据结构。
今天详细分析源码(JAVA 1.8)
一、HashMap 成员变量 与初始化
先说几个默认值
/**
* 默认初始容量16
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大容量 2 的 30 次方
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默认负载因子 0.75
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 链表转红黑树的阈值 8(链表长度大于 8,可能转红黑树)
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 红黑树转链表的阈值 6 (红黑树节点小于 6,红黑树退化为链表)
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 当容量大于64,链表可转红黑树,容量小于64,优先扩容
*/
static final int MIN_TREEIFY_CAPACITY = 64;
HashMap 有一个内部类Node,key-value 的值就存在Node 中
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
}
在上一篇博客中,说到的数组,数组的元素就是 Node对象
下面是几个成员变量比较关键
/**
* 数组对象,用来存放Node
*/
transient Node<K,V>[] table;
/**
* 键值对,遍历时用
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* HashMap 中实际存了多少个键值对
*/
transient int size;
/**
* 修改次数(快速失败机制用)
*/
transient int modCount;
/**
* 阈值(达到这个值时,就启动扩容),大小等于 容量*负载因子
*/
int threshold;
/**
* 负载因子(前面说的那个 0.75是默认的值)
*/
final float loadFactor;
初始化方法
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
这里顺便说一下,如果在使用HashMap时,明确知道要放入多少个键值对。
那推荐用第一个初始化方法,即传入容量大小,这样操作过程中,可以避免扩容。
上面说 transient Node<K,V>[] table
,这个数组大小,
它和 HashMap 中存入多少键值对,即参数 transient int size
不是严格对应的。
因为出现哈希冲突时,一个位置实际是存储了多个键值对。
table
可以近似的理解为,火车上有多少个座位;
size
则是实际上火车上有多少乘客。
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);
}
这段是初始化最终调用的代码,这里并没有 new 一个数组出来。
这没什么意外的,数组要连续的内存空间,等用的时候,才会 new 一个数组过来。
这个等讲 扩容 的时候再详细说。
this.threshold = tableSizeFor(initialCapacity)
这段很重要。
先记住结论:tableSizeFor(initialCapacity)
,返回的是 2 的 n 次方。
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
关于这段代码的解析,本篇不讲,可以看我以前的博客《2的n次方是怎么玩儿的》。
二、添加元素
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
在 put
方法中,先说 hash(key)
。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
key 的 hashCode 值为 h, h 高 16位 与 h 本身,做 异或运算。
这个本身不难理解,据说这样做的好处:让高位也参与运算,可减少哈希冲突
hashMap
中采用的哈希函数是 hash & ( n-1 )
。
这里面 hash 就是上面那个 高16位参与的异或运算的结果, n 指的是数组的长度。
hash & ( n-1 )
计算的结果,和 hash%n
计算的结果是一样的。
这个不懂没关系,记住就行,哈希函数就是计算数组下标的,
hash%n
得到的就是下标,这个好理解。在我之前的博文中,
详细说明了《为什么hash & ( n-1 ) = hash%n》。
我们接着看 put
方法。
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;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
(tab = table) == null || (n = tab.length) == 0
这行指的是数组为空,调用 resize 方法,返回新数组。
put
方法的总逻辑是,计算出下标,看数组中该下标有没有放元素。
若没有,则直接设置新值,若有元素,判断是链表还是红黑树,再进行相应的追加。
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
这个判断就是看看,该下标处有没有元素,没有,直接设置。
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
这个的意思是,该下标本身存储有元素,而且 key 相同。
啥意思呢 上面那个图我想往数组里放(东邪 99),发现旧值 (东邪 100)在那。
通常情况下,哈希冲突的可能性很小,也就是说,很大概率该下标处有存储元素,
那这个元素的key,与传入的key是一样的。
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
这行,是该下标处,存储的是一个红黑树,那执行插入红黑树节点的方法 putTreeVal
。
这个红黑树代码复杂,本文不讲。(其实是我不会,也不想去看,哈哈 )
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;
}
执行这段代码,说明是该下标处是一个链表,头节点的key 与传入的 key 不一样。
这时的执行逻辑就是,从链表第二个元素开始比较(第一个前面比较过了)。
如果链表中 key 存在,则跳出循环,如果 key 下存在,则 new 一个新节点,追加到链表最后。
binCount 是用来计算链表长度的,如果链表长度达到 8,执行 treeifyBin(tab, hash);
,
也就是转化为红黑树,这个方法等会儿讲。
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
这段代码,意思是在该下标处,找到了 key,也就是说存在旧值,作相应的处理。
不存在旧值的情况,上面说过了,new 从此新节点,放进去。
onlyIfAbsent 这个参数在本例中是 false,就是要替换旧值。
@param onlyIfAbsent if true, don't change existing value
这个源码中对这个参数的解释。
说有很明白,当这个参数是 true
时,不替换旧有的值。
if (!onlyIfAbsent || oldValue == null)
后半段的判断,旧值是 null,一定会替换。
顺便说一句:HashMap 中 key、value都允许是 null。
++modCount; // 记录 HashMap 的改动次数
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
if (++size > threshold)
这行,是指 HashMap 中存的键值对,达到了一定数量,自动扩容。
threshold
是阈值,在默认情况下,数组大小为 64,负载因子是 0.75,
threshold = 64*0.75 = 48
。 也就默认初始化的情况下,存入 48 个键值对,
就进行第一次扩容,哪怕这48个元素都在一个下标处。
至此为止,put 方法除了 resize()
和 treeifyBin(tab, hash)
之外,其它都详细讲了一遍。
简单总结就是,
- 算出 key 对应的下标(根据哈希函数计算)
- 该下标处未存值,那直接new 个新节点,放进去,返回null
- 下标处有存值,看该位置的key 与 传入的key 是不是同一个,若是,则设置新value,并返回旧value。
- 前面的不满足,若该位置是红黑树,插入红黑树的节点。
- 该位置是链表,遍历链表寻找相同的key,找到了就设置新value,返回旧value
- 如果没找到,new 一个新的节点,插入到链表末尾,过长就链表转红黑树
三、扩容与链表转红黑树
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);
}
}
看这行 if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
数组长度小于64,扩容
也就说,数组长度小于64,不会出现红黑树。
数组长度大于等于64,且链表长度大于8,链表转红黑树。
TreeNode
是间接继承了 Node
。
// For treeifyBin
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}
replacementTreeNode 这个方法就是将 node 节点,换成对应的 TreeNode 节点。
这里 do{} while()
就是将链表中的每个节点,逐一转换为 TreeNode 节点的链表。(当然是建了一个新链表哈)
if ((tab[index] = hd) != null)
hd.treeify(tab);
这段是将前面那个新链表,转化为红黑树,本文不讲(真的是我不会,也不想去研究,红黑树代码啦 )。
.
详细说下 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) {
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)
((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;
}
别看这代码巨长,其实逻辑很简单。
看下 put 方法,第一个逻辑是
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
就是数组不存在,调用 resize()
,那下面这段,得到的 oldCap 就是 0。
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
那 代码就会进这个分支
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
newCap
就是 oldThr
,也就是初始化时,this.threshold = tableSizeFor(initialCapacity)
这段的执行结果。
即结果是 2 的 n 次方。
当第二次调用 resize 方法时,oldCap 大于 0 。
会执行 newCap = oldCap << 1
,即变为原来的两倍。
那数组的大小,始终是 2 的 n 次方。
如果不这样 hash & ( n-1 )
,这个哈希函数就失效了。
好也,现在前后都串起来了。
- 初始化时,没有数组,只有
threshold
,一定是 2 的 n 次方 - 首次调用
resize
时,newCap会等于 初始化的threshold
,即 2 的 n 次方 - 再次调用
resize
时,newCap 会等于 oldCap 的两倍,依旧是 2 的 n 次方
这些是哈希函数生效的基础,不知道为啥,看这篇《为什么hash & ( n-1 ) = hash%n》。
然后,再说下扩容后,元素是怎么转移的。
以链表为例,(e.hash & oldCap) == 0
用这个判断,生成两条链表。
生成一个新数组,大小是原数组两倍。
一条在原坐标 i 处,另一条在 i + n 处(n 原数组大小)。
先记住上面的结论和效果,现在结合代码一条一条讲清楚。
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)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else {
.......
}
}
}
}
return newTab;
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]
这是new 一个新数组,两倍大。
for (int j = 0; j < oldCap; ++j)
这是下标一个接一个处理。
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
这行,是该下标只有一个元素,那计算新下标,直接设置。
顺便说一下,新下标只有两种可能,和原来的相等,或者在原来基础上+原数组大小。
计算下标的公式 hash & (n-1) = hash % n
这个不再解释。
17 % 4 = 1, 17 % 8 = 1 ------- 13 % 4 = 1, 13 % 8 = 5
数组扩大两倍后,算下标,要么和原来的相等,或者在原来基础上+原数组大小。
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
这个意思是该节点是红黑树,那按红黑树的逻辑来处理,本文不讲。
该节点是链表时,源码如下
else {
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
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;
}
}
Node<K,V> loHead = null, loTail = null;
这个是下标和原来相等那种情况,链表头和链表尾。
Node<K,V> hiHead = null, hiTail = null;
这个是另外一条链表的,链表头和链表尾。
(e.hash & oldCap) == 0
这个判断为 true,就是下标和原来相等,为 false 就是另外那种情况。
do { } while ((e = next) != null);
这个循环,做的逻辑是:
原链表从头开始,分成两队,拼出两条新的链表。
熟悉链表的,这段代码不难理解,不深入解释。
详细下这个 (e.hash & oldCap) == 0
。
假设原数组长度是4,扩容后长度是8。
那原来计算下标:hash & 3
,即得到二进制的最后两位。
扩容后计算下标:hash & 7
,即得到二进制的最后三位。
那新旧下标是否相等,就是看 二进制的倒数第三位,如果是0,那就相等,否则不相等。
hash & oldCap
那得到的不就是二进制的倒数第三位么!
if ((e.hash & oldCap) == 0) {}
这个判断,就讲到这,懂就懂了,不懂写几个数字,自己算算。
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
这段是将链表放到对应位置。
resize() 方法讲完了,很可能这是你看过的,本篇讲的是最详细的。
王婆卖瓜,自卖自夸!哈哈……
.
四、查找元素
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;
}
getNode 这个方法,就是查找对应的node。
首先,如果数组为null,或者数组长度为 0,直接返回 null。
其次,tab[(n - 1) & hash] == null
,那就是相应下标没有元素,直接返回 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);
}
这段的意思是,该下标处的元素key 与传入的key 不同,那就比对下一个。
如果是红黑树,那走红黑树的逻辑。这个我不会,不讲。
如果是链表,逐一比对,如果key一致,就返回,否则返回 null。
五、删除元素
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,
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;
}
remove
方法,前面一半,是找对应的节点,并记录它的父节点。
查找对应结果,和 get
方法差不多。
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;
第一个分支,是红黑树,不讲。
第二个分支,指的是父节点恰好是头节点,将链表的第二个节点放数组里。
第三个分支,指父节点不是头节点,那将 与 key 相同的节点,直接删除。
六、遍历
@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();
}
}
这里只说一点, if (modCount != mc)
意思是在遍历过程中,HashMap数据有改动,那就抛出异常。
modCount 这个用来记录变动了多少次,put 和 remove 方法中都有维护。
所谓的快速失败机制(fast-fail)。hashMap 没有线程安全的相关措施,这种算是一个补偿吧。