Java中的HashMap采用链地址法(数组+链表)解决哈希冲突。并且随哈希表中节点(键值对)增加时,能够进行扩容和链表转红黑树操作。扩容是为了增加槽位,以容纳更多的节点,策略是每次扩容二倍。而链表转红黑树是发生在每个槽位上(满足一定条件时),在链表中顺序添加、查找和删除某个元素的效率很低(n),而红黑树中相应的操作效率要高(lgn)。
HashMap中的几个静态字段:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认初始容量(哈希表中的桶数、即数组大小)
static final int MAXIMUM_CAPACITY = 1 << 30; // 最大容量(桶最大数量、即数组最大长度)
static final float DEFAULT_LOAD_FACTOR = 0.75f; // 默认负载因子
static final int TREEIFY_THRESHOLD = 8; // 链表转红黑树阈值(>=)
static final int UNTREEIFY_THRESHOLD = 6; // 红黑树转链表阈值
static final int MIN_TREEIFY_CAPACITY = 64; // 进行链表转红黑树的最小容量(桶数、即数组大小)值。当容量小于此值时,不转换,而是进行扩容(resize)
HashMap中成员字段:
transient Node<K,V>[] table; // 哈希槽,每个槽中存放链表头结点或红黑树中第一个节点(不是根节点)
transient Set<Map.Entry<K,V>> entrySet; // 保存节点的Set集合
transient int size; // 当前节点数量
transient int modCount; // 修改次数(包括增加、删除、resize等)
int threshold; // 阈值(threshold=capacity*loadFactor),一旦node数量超过(>)这个值,就要重哈希(rehash),进行resize
final float loadFactor; // 负载因子,一旦哈希表中装载程度(当前size/capacity)超过这个数值,就要重哈希。
容量计算:
HashMap的容量(capacity)值要取2的幂,所以当初始容量值不是2的幂要通过tableSizeFor方法重新计算。tableSizeFor方法通过五次无符号右移操作即可求出符合条件的容量值。
/**
* tableSizeFor能够计算出一个大于等于并且最接近与cap值的2的幂
* 具体算法:设cap二进制值为
* 1 x x x x x x x
* x为0或1,第一个1代表最高有效位
* n |= n >>> 1 后,能够保证n的二进制值前两位有效位都为1
* 1 1 x x x x x x
* n |= n >>> 2 后,能够保证n的二进制值前四位有效位都为1
* 1 1 1 1 x x x x
* n |= n >>> 4 后,能够保证n的二进制值前八位有效位都为1
* 1 1 1 1 1 1 1 1
* 因为cap有效位一共八位,所以后续步骤n值不在变化,而n+1就是不小于cap的2的次幂
*/
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;
}
resize操作:
resize方法中,首先根据一系列前置条件,以确定新容量(newCap)和阈值(newThr),然后重新创建一个数组,接着把原哈希表中元素(如果有的话)重新装入新哈希表。这个过程涉及到了hash值到槽位(数组下标)的重新映射,也就是33行的if块。
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) {
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;
}
这里比较有意思的地方就是else块中的逻辑,进入else块中的条件:原桶中为链表且节点数量大于1。
/**
* e.hash & oldCap 的值代表什么?
* 每一个key在选择桶位时是根据(n - 1) & hash进行分配的,当扩容后,newN=n*2
* 再次计算每一个key的桶位置时,就应该通过计算(newN - 1) & hash来确定
* 同一个旧桶中,能够知道每个key的hash值计算出的(n - 1) & hash都相等,而对此hash值
* 计算(newN - 1) & hash时,只要hash值二进制的第n位为0,那么与原桶位相同,而
* 第n位为1时,则新桶位应该为n + (n - 1) & hash
*
* 如:n=8, n-1 = 7 (0111)
* key1 hash = 10010110
* key2 hash = 11010110
* key3 hash = 10001110
* key4 hash = 01011110
* 四个key哈希值末三位都为110,即桶位都为3
* 扩容后(二倍),求新桶位时,需要取低四位,若hash值第四位为0,则桶位仍未3(110),若为1,则为4+3=7(1000+110,即n+j)
* 也就是说哈希表二倍扩容后,原来某个桶j中的节点会被重新分配到两个新桶位j和n+j
*/
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) { // 将桶位置不变(j)的节点按需连接成链表
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else { // 将桶位置该变(j+oldCap)的节点按需连接成链表
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) { // 将桶位置不变(j)的链表装入新哈希表的桶(j)中
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) { // 将桶位置改变(j+oldCap)的链表装入新哈希表的桶(j+oldCap)中
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}