相同系列:
一、HashMap源码分析——默认参数问题
二、HashMap源码分析——put、get方法
相关字段
/* ---------------- Fields -------------- */
transient Node<K,V>[] table;
transient int size;
int threshold;
final float loadFactor;
/*
1、Node<K,V>[] table就是哈希表,这个Node就是上篇的普通节点,它记录了哈希值、K、V、还有下一个节点的信息
2、size就是当前K-V键值对的数量
3、阈值threshold,当size>threshold时,就会发生扩容,重新散列
4、loadFactor就是当前的负载因子值
*/
hash方法
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
为什么要key的哈希值高16位参与运算?
注释大意+个人理解:
1、避免出现高位频繁变动而低位很少变动的情况,让hash值更随机,有利于减少哈希冲突。
2、采用与高16位异或运算,是利用最少的代价来减少系统性能的损失。
tableSizeFor方法
一个保证哈希表容量是2次幂的方法。看下方代码,可以看到这个位运算操作像是在给最高位的1做复制翻倍的效果,最后得到一个2次幂-1的结果,然后+1就得到一个2次幂的结果。
int tableSizeFor(int cap) {
int n = cap - 1; //1xxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
n |= n >>> 1; //11xx xxxx xxxx xxxx xxxx xxxx xxxx xxxx
n |= n >>> 2; //1111 xxxx xxxx xxxx xxxx xxxx xxxx xxxx
n |= n >>> 4; //1111 1111 xxxx xxxx xxxx xxxx xxxx xxxx
n |= n >>> 8; //1111 1111 1111 1111 xxxx xxxx xxxx xxxx
n |= n >>> 16; //1111 1111 1111 1111 1111 1111 1111 1111 (2^k)-1
return (n<0)?1:(n>=MAX_CAPACITY)?MAX_CAPACITY:n+1; //+1
}
另外,将元素定位到哈希桶的运算是hash&(n-1)
,其中n是哈希表的容量,因为保证了n是二次幂,所以决定了扩容时,必须将容量扩达到2倍(2次幂倍数)。
hash&(n-1)的结果从二进制上看,设n=2^k,其实就是hash值对应二进制的低k位结果。
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 { // 链表拆分
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&oldCap来分组
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;
}
源码部分解析
1、resize方法怎样扩容的?
实际上是新建了另一个哈希表,然后重新定位元素到新的哈希表中。
2、链表拆分中的hash&oldCap
是怎么回事?
前面说过定位的运算是hash&(n-1),其中n=2^k,这里oldCap就相当于n。
- hash&(n-1)的结果是hash二进制下的低k位
- 在同一个桶内的元素的hash值的低k位是相同的
- 重新定位的运算是hash&(newCap-1),就是看hash二进制下的低k+1位是否相同
综上,元素重新定位到新的哈希表中,只要看hash值二进制下的第k+1位是否相同即可,相同的会在同一个桶内。hash&oldCap
的结果就是看hash值二进制下的第k+1位是0还是1的。如果是0,则表示还是在这个下标的桶里边,否则的话,就进行二次幂的移动(因为这时,hash & (newCap-1) = hash & (oldCap-1) + oldCap
,所以会在原位置的基础上,向右移动oldCap个位置,对应源码 newTab[j + oldCap] = hiHead;
)。