java8 HashMap源码解析
HashMap
在java7中,HashMap的数据结构由数组和链表组成。
put时,将key按照hash算法计算出在数组中的索引,将键值对存放在数据中,如果遇到hash碰撞,就构造链表。
链表查询数据的时间复杂度o(n),随着hash碰撞越来越多,链表就越来越长,数据的查询就会越来越慢
跟java7相比,java8对HashMap的数据结构做了优化,很大程度上的优化了性能。
在java8中,HashMap的数据结构由数组和链表和红黑树组成
put时,将key按照hash算法计算出在数组中的索引,将键值对存放在数据中,如果遇到hash碰撞,就构造链表,当链表的长度达到8时,就将链表转为红黑树,红黑树的查询时间复杂度是o(log(n))
我们把数组中的每一个元素称之为‘桶’,桶中存储的元素要么是一个单独的node,要么是一个链表或者红黑树
我们先来看下HashMap中链表的数据结构
/**
* 代表一个链表或者数组中的一个节点
*/
static class Node<K,V> implements Map.Entry<K,V> {
// key的散列值
final int hash;
final K key;
V value;
// 链表中的下一个节点
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
/**
* 代表红黑树中的一个节点
*/
static 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);
}
...
}
篇幅有限,本篇不涉及任何关于红黑树内容
我们先来看下类中的一些变量
/* ---------------- Fields -------------- */
/**
* 这个数组就是图中的那个数组结构,每个下标所在的位置都是一个‘桶’
* 这个变量在第一次put时初始化,它的长度必须是2的幂,原因我们后面再说
*/
transient Node<K,V>[] table;
/**
* 存储缓存的键值对
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* 键值对的数量
*/
transient int size;
/**
* 这个值同来统计哈希表变动的次数
*/
transient int modCount;
/**
* 哈希表中能存储的元素的最大值,超过这个值,哈希表就会扩容
* threshold == loadFactor * table.length
*/
int threshold;
/**
* 加载因子,定义哈希表什么时候扩容
*/
final float loadFactor;
我们先来看下构造方法
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);
}
我们主要看下threshold 是怎么初始化的,在第一次put时需要resize,此时会把threshold 的值作为table的长度,所以它的值必须初始化为2的幂。
tableSizeFor
/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
tableSizeFor返回一个大于或等于 cap 的最小2的幂。
熟悉计算机的可以忽略这节的内容了,直接看下一节就行了。
我们来分析下这个算法
最小的2的幂是2,以二进制数表示
0000 0000 0000 0000 0000 0000 0000 0010
把一个数左移一位,相当于乘以2,
2^2 = 0000 0000 0000 0000 0000 0000 0000 0100
2^3 = 0000 0000 0000 0000 0000 0000 0000 1000
2^4 = 0000 0000 0000 0000 0000 0000 0001 0000
而任何一个2的幂可以以这样的方式得到
0100 0000 0000 0000 0000 0000 0000 0000
=
0011 1111 1111 1111 1111 1111 1111 1111 +
0000 0000 0000 0000 0000 0000 0000 0001
所以我们可以得出想出这样的算法:对于一个二进制数n,把它从最高有效位开始全部置1得到数m,再把m加1,得到数y,y肯定就是比n大,且离n最近的2的幂。我们举个栗子
0100 0100 0100 0101 0010 1111 0100 0001
↓
0111 1111 1111 1111 1111 1111 1111 1111 + 1
=
1000 0000 0000 0000 0000 0000 0000 0000
那该怎么用程序实现呢?我们的目标应该是把所有有效位变成1,我们来整理下思路
因为一个二进制数n的最高有效位肯定是1,我们把n右移一位,那n的最高有效位肯定还是1,只不过最高有效位,向右移动了一位,我们知道2个数进行或运算,只要位值是1那结果也肯定是1,所以就有:
n = n | (n >>> 1)
此时n的最高有效位前2位肯定都是1了!
那么我们再把n向右移动2位,再进行或运算
n = n | (n >>> 1)
n = n | (n >>> 2)
此时n的最高有效位前4位肯定都是1了!
那么我们再把n向右移动4位,再进行或运算
n = n | (n >>> 1)
n = n | (n >>> 4)
此时n的最高有效位前8位肯定都是1了!
那么我们再把n向右移动8位,再进行或运算
n = n | (n >>> 1)
n = n | (n >>> 8)
此时n的最高有效位前16位肯定都是1了!
那么我们再把n向右移动16位,再进行或运算
n = n | (n >>> 1)
n = n | (n >>> 16)
此时n的最高有效位前32位肯定都是1了!
因为整数是32位,一个数向右移动,超过的部分会被丢弃,比如
0000 1000 1111 1111 1111 1111 1111 1111 >>> 27
=
0000 1111 1111 1111 1111 1111 1111 1111 1111
=
0000 1111 1111 1111 1111 1111 1111 1111 //最后4位被丢弃
所以对于一个数n,经过以下运算
static final int doubleNumber(int cap) {
int n = cap;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;//此时从最高有效位开始全是1
return n + 1;
}
此时n肯定就是比n大,且离n最近的2的幂。
对于一个非2的幂的数n,计算的结果肯定不受到除最高有效位的其它低位的影响
doubleNumber(n- 1) == doubleNumber(n)
对于一个2的幂数n,对最高位来说 n - 1 只是把最高位向右移动了一位而已
0100 0000 0000 0000 0000 0000 0000 0000 - 1
=
0011 1111 1111 1111 1111 1111 1111 1111
我们发现doubleNumber的效果其实就是把最高有效位左移一位,其它位置0,
所以,对于一个2的幂数n,n = doubleNumber(n - 1)。
所以这就是tableSizeFor为啥这么设计的原因了:
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;
}
put
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
因为篇幅有限,写多了好卡。。。
hash函数的分析看下面这篇博客
我们再来看下putVal,先说下流程:
- 计算key的hash
- 如果是第一个插入数据,需要先初始化table
- 根据hash计算key在table中的下标位置i
- 如果table[i]处没有数据,将key插入到该位置,否则
- 如果i处是一个链表,则从头部开始遍历,将每个节点与key进行对比,如果相同则用新的value值替换并返回旧的value值,否则将key保存在链表尾部,如果此时链表的长度达到了8,先判断table的长度是否达到64,如果是就把链表转成红黑树,否则就扩容
- 如果i处是一个红黑树,逻辑跟链表类似
- 如果hash表中多了一个元素,且元素的数量达到了阈值就进行扩容
/**
* @param hash key的hash值
* @param key
* @param value
* @param onlyIfAbsent 等于true时,不改变key对应的value值,除非key对应的value为null
* @param evict false代表hash表是creation模式,子类才会使用这个参数
* @return 返回老的value,如果不存在就返回null
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 初始化tab
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// i = (n - 1) & hash]计算key在table中的下标
// 无碰撞,直接插入node
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 存在碰撞,且碰撞处头结点与key就是同一个对象
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) {
// 链表中不存在key对应的node,直接插入到链表尾部
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 链表长度达到8,转成红黑树结构
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 链表中已经存在key对应的node了
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// key相关的node已经被插入过了,直接返回旧的value值
if (e != null) {
V oldValue = e.value;
// onlyIfAbsent == true时,key已经存在,返回旧值
// onlyIfAbsent == false时,key不存在,插入新值
// oldValue == null时,必须插入新值
if (!onlyIfAbsent || oldValue == null)
e.value = value;
// 子类需要重写
afterNodeAccess(e);
return oldValue;
}
}
// 新的key第一次插入
++modCount;
// 插入的元素数量达到了阈值需要扩容
if (++size > threshold)
resize();
// 需要子类重写
afterNodeInsertion(evict);
return null;
}
在第一次put前,table是没有初始化的,需要resize()函数进行初始,当插入一个新的key时,如果key的数量达到了阈值,就需要resize()扩容
/**
* table扩容,大小变成原来的2倍,原来桶中的元素要么还是待在原来的下标位置
* 要么以2的幂为偏移进行移动
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// table已经初始化的情况
if (oldCap > 0) {
// table的大小不能超过MAXIMUM_CAPACITY
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//table大小变成原来的2倍,节点阈值变成原来的2倍
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
// table大小=原来键值对的阈值
newCap = oldThr;
else {// 未使用了带参数构造方法
newCap = DEFAULT_INITIAL_CAPACITY;//16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//12
}
// 计算扩容后的阈值
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;
// j处的桶不是空的
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// 桶中只有一个元素时直接将该元素移动新表中
// 注1:e.hash & (newCap - 1)为元素在新表中的位置
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
// 扩容后,元素的的位置要么无偏移,要么偏移oldCap,
// 有无偏移分别构造不同的链表
// loHead为无偏移时的链表头,loTail为无偏移时的链表尾
Node<K,V> loHead = null, loTail = null;
// hiHead为有偏移时的链表头,hiTail为有偏移时的链表尾
Node<K,V> hiHead = null, hiTail = null;
// next用来标记当前元素
Node<K,V> next;
do {
next = e.next;
/**
* oldCap最高有效位是1,低位全是0
* (e.hash & oldCap) == 0
* 说明oldCap最高有效位对应的hash位是0
* 所以根据注1中的说明,代表进行扩容后元素无偏移,
* e的位置不变
*/
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;
}
// 将桶插入到新表,偏移为oldCap
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
注1
table扩容后,元素的的位置要么无偏移,要么偏移oldCap,算法如下
e.hash & (newCap - 1)
前面已经说过这个算法了,我们还是用二进制表示来分析
假设oldCap = 16
16 = 0000 0000 0000 0000 0000 0000 0001 0000 - 1
= 0000 0000 0000 0000 0000 0000 0000 1111 &
h = 0100 1000 1100 0001 0101 0011 1110 0011
= 0000 0000 0000 0000 0000 0000 0000 0011
ind = 3
//扩容后
32 = 0000 0000 0000 0000 0000 0000 0010 0000 - 1
= 0000 0000 0000 0000 0000 0000 0001 1111 &
h = 0100 1000 1100 0001 0101 0011 1110 0011
= 0000 0000 0000 0000 0000 0000 0000 0011
ind = 3
结论:ind未变
我们可以发现,扩容后ind的值取决于掩码的最高有效位(例子中是第5位)对应的hash位是0还是1,
如果是0,ind不变,如果是1,ind的偏移为oldCap,即偏移为原来table的大小,例如:
16 = 0000 0000 0000 0000 0000 0000 0001 0000 - 1
= 0000 0000 0000 0000 0000 0000 0000 1111 &
h = 0100 1000 1100 0001 0101 0011 1111 0011
= 0000 0000 0000 0000 0000 0000 0000 0011
ind = 3
//扩容后
32 = 0000 0000 0000 0000 0000 0000 0010 0000 - 1
= 0000 0000 0000 0000 0000 0000 0001 1111 &
h = 0100 1000 1100 0001 0101 0011 1111 0011
= 0000 0000 0000 0000 0000 0000 0001 0011
ind = 3 + 2^4 = 19
get
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
我们再来看下getNode,先说下流程:
- 计算key的hash值得到hash
- 检查table是否初始化且key在桶里面,如果不是直接返回null,否则继续第3步
- 检查桶中的第一个元素是不是key,是直接返回,否则继续第四步
- 遍历桶,找到与key相同的元素返回
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
/**
* (tab = table) != null && (n = tab.length) > 0
* 说明table已经初始化
* (first = tab[(n - 1) & hash]) != null
* 说明key肯定已经存在桶里了
*/
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 桶中的第一个元素就是key,直接返回,免得去循环遍历桶
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 链表的元素大于1
if ((e = first.next) != null) {
// 红黑树
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
// 从链表中遍历直到找到相同的key
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
remove
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
我们再来看下removeNode,先说下流程:
- 计算key的hash值得到hash
- 检查table是否初始化且key在桶里面,如果不是直接返回null,否则继续第3步
- 检查桶中的第一个元素是不是key,是直接删除,否则继续第四步
- 遍历桶,找到与key相同的元素删除
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;
/**
* (tab = table) != null && (n = tab.length) > 0
* 说明table已经初始化
* (p = tab[index = (n - 1) & hash]) != null
* 说明key肯定已经存在桶里了
*/
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;
// 桶中的第一个元素就是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<K,V>)p).getTreeNode(hash, key);
else {
// 从链表中遍历直到找到相同的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);
}
}
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;
}