# Java8 HashMap扩容算法实例解析

Java8的HashMap扩容过程主要就是集中在resize()方法中

``` final Node<K,V>[] resize() {
// ...省略不重要的
}```

```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)
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
}
if (hiTail != null) {
hiTail.next = null;
}
}
}
}

final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
// ...省略不重要的
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
// ...省略不重要的
}```

n-1　　 ----> 0x0111

hash1 & n-1 = 0x0101

hash2 & n-1 = 0x0101

hash1 & n = 0x0000

hash2 & n = 0x1000