本篇文章不讲HashMap是什么样的数据结构,
只讲一下HashMap中用到的比较巧妙的算法,如何去优化扩容的。
put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
在putVal方法之前,对 key 进行了 hash 计算。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
通过 hashCode() 方法和无符号左移16后的 hashCode 进行异或计算。 进行了一次扰动计算。
再看 putVal 方法中。如何计算 key 再数组中的下标。
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;
}
在第 6 行中, tab[i = (n – 1) & hash] 计算下标,使用了 hash 值跟 n-1 进行位与运算。
第一次初始容量为 16, hash 值跟 15 进行位 与运算。而 15 的二进制是 1111。得到的是 hash 值的前 4位二进制。所以得到的结果就是,0-15之间的数字,正好是数组下标。
假如容量已经扩展,那现在的容量为 2n,hash 值跟 2n-1 进行位 与运算, 得到的是 hash 值的前 n 位二进制。
resize方法
原本的扩容方式就是将数组变长,对每个节点数据重新计算下标,但是1.8版并不是这样做的。看看源码:
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) { // 将hash 与 16 这种 2n 进行 与操作,计算新增的一位bit 是0,还是 1。
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) { // 0 该节点还存原下标位置
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) { // 1 该节点由原下标位置向后移动 2n 位置
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
新版 hashMap 对扩容进行了优化,当容量扩充为原来的 2 倍时,只需判断新增的一位 bit 是0还是1。
例如,当由 16 扩充至 32 时,16 的 二进制时 10000,与 hash 计算,得到的是第 5 位 bit 的值。
原本计算下标,只是与前 4 位进行与运算,现在扩容一次后是对前 5 位进行与运算。
扩容方法里面并没有重新计算所有位的与运算,只需判断新增的第 5 位。减少了计算量。
原创文章,如有什么不对,欢迎指出。