风筝有风,海豚有海
1.8中的尾插
下面是JDK8的HashMap
里的扩容代码里数据转移的部分
final Node<K,V>[] resize() {
......
// newTab就是新的哈希表,现在需要从旧表往新表做数据转移
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) { // 【1】
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e; //【2】
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else {
// 【3】
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);
// 【4】
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
- 【1】:没有元素的槽位自然不需要数据转移
- 【2】:当该槽位只有一个元素的时候,只需要转移该元素即可。JDK8中HashMap的容量有特定值,对于长度为n的散列表,可以用哈希值&(n-1) 的方式获取其散列位置。
- 【3】:因为JDK8中HashMap的容量一定是
2
n
{2^n}
2n,再配合翻倍扩容,所以可以快速得出某元素在newTab中的散列位置,
(e.hash & oldCap) == 0
时,代表元素散列位置没有变换(相当于时钟连一圈都没转弯),反之则应散列到j + oldCap
处。这才是规定容量一定是${2^n}$的意义
- 【4】:之前的版本中的HashMap在多线程时,可能在扩容时造成尾节点的next指针指向前面元素,从而可能在下次使用时触发死循环,所以这里直接杜绝了这种可能。
1.7中的头插
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);【1】
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
- 头插法
- 【1】:其方法时
h & (length-1);
,可见,如果单纯从获取散列位置来讲,与Java8差不多,但是Java7的数据迁移率要高不少。那么问题来了
1.6中的头插
void transfer(Entry[] newTable) {
Entry[] src = table;
int newCapacity = newTable.length;
for (int j = 0; j < src.length; j++) {
Entry<K,V> e = src[j];
if (e != null) {
src[j] = null;
do {
Entry<K,V> next = e.next;
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
} while (e != null);
}
}
}
- 散列函数与1.7是一样的
- 与1.7基本一样,但是还有点细微差别~不知道作者心路历程是什么