一、JDK7
(一)解读
1、数据结构
JDK1.8之前的HashMap的实现方式是数组+链表
2、劣势
HashMap单个槽下是一条链表,遍历链表的时间复杂度是O(n),失去了快速检索的优势
针对这种情况,JDK1.8引入了红黑树来优化
二、JDK8
(一)解读
1、数据结构
JDK1.8的HashMap的数据结构是数组+链表+红黑树的形式,当HashMap容量>64 and 链表长度>8之后,每个槽的数据结构转为红黑树;当Node删除至链表长度<6时,再次转变为链表。源码如下:
// 桶的树化阈值 static final int TREEIFY_THRESHOLD = 8; // 最小树形化容量 static final int MIN_TREEIFY_CAPACITY = 64; // 树的链表还原阈值 static final int UNTREEIFY_THRESHOLD = 6; // JDK1.8新增的桶的树形化操作 final void treeifyBin(Node[] tab, int hash)
对桶的树形化操作的解读:
final void treeifyBin(Node[] tab, int hash) { int n, index; Node e; // 根据哈希表中的元素个数确实是扩容还是树形化 // 如果当前哈希表为空——>resize()新建数组 || 哈希表中元素个数小于64——>扩容数组 if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); // 确定不是扩容而是树形化操作 // (n-1)&hash——>获取数组下标的操作(伴随扩容后的rehash) // 获取到新的哈希值之后,判断该下标的槽不为空,e为该槽下链表第一个节点,执行尾插法 else if ((e = tab[index = (n - 1) & hash]) != null) { TreeNode hd = null, tl = null; // 链表复制 do { // 不断复制内容,新建节点,建立新联系 TreeNode p = replacementTreeNode(e, null); if (tl == null) hd = p; else { p.prev = tl; tl.next = p; } tl = p; } while ((e = e.next) != null); // 让桶指向新建红黑树的头结点 if ((tab[index] = hd) != null) // 链表转红黑树 hd.treeify(tab); } }
2、HashMap的put操作
源码:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node[] tab; Node p; int n, i;
// 步骤一:tab为空,调用resize()创建/扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 步骤二:根据hash值计算下标,得到索引
// 为空则直接插入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node e; K k;
// 步骤三:不为空,查看key值是否存在
// 存在,则直接覆盖
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 步骤四:判断该链是否为红黑树
// 是则直接插入节点
else if (p instanceof TreeNode)
e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
// 为链表,执行链表的插入操作
else {
for (int binCount = 0; ; ++binCount) {
// 到叶子结点后,key仍不存在,执行插入操作
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 步骤五:链表长度大于8,链表转化为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 步骤六:key已存在,退出循环
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;
}
}
// HashMap修改次数+1
++modCount;
// 步骤七:如果超过threshold,即超过最大容量capacity*loadFactor,就扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
3、get操作
源码:
public V get(Object key) {
Node e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node getNode(int hash, Object key) {
Node[] tab; Node first, e; int n; K k;
// 判断哈希表不为空,且槽节点也不为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 判断第一个节点是否满足
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 遍历后续节点
if ((e = first.next) != null) {
// 判断是否是红黑树,是则调用getTreeNode找节点
if (first instanceof TreeNode)
return ((TreeNode)first).getTreeNode(hash, key);
// 链表,一直向后找,找对应key的节点
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
4、remove操作
源码:
public V remove(Object key) {
Node e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node[] tab; Node p; int n, index;
// 同get()的第一步,判断哈希表不为空,且槽节点也不为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node node = null, e; K k; V v;
// 判断第一个节点是不是待找寻节点
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
// 后续不为空,从红黑树或链表继续找
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
// 对上部标记的待删除node,判断value是否匹配,进行删除操作
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
// 红黑树节点删除
if (node instanceof TreeNode)
((TreeNode)node).removeTreeNode(this, tab, movable);
// 链表头结点删除
else if (node == p)
tab[index] = node.next;
// 链表中间节点删除
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
5、hash()方法
原理:HashMap使用二次扰动机制来尽可能降低哈希冲突的概率,二次扰动过程见下方
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
6、resize()方法
final Node[] resize() { Node [] 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; } // 还没到最大容量,容量*2 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); } // 最终确认新的resize阈值 threshold = newThr; // 创建新的哈希表 @SuppressWarnings({"rawtypes","unchecked"}) Node [] newTab = (Node [])new Node[newCap]; table = newTab; if (oldTab != null) { // 遍历旧表,重新计算新位置 for (int j = 0; j < oldCap; ++j) { Node 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 )e).split(this, newTab, j, oldCap); // 处理链表 else { // preserve order Node loHead = null, loTail = null; Node hiHead = null, hiTail = null; Node 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; }
(二)原理
1、数组扩容
(1)扩容情况:
- 当HashMap中的元素个数超过数组大小(数组长度)*loadFactor(负载因子)时,就会进行数组扩容,loadFactor的默认值(DEFAULT_LOAD_FACTOR)是0.75,这是一个折中的取值。
- 注意:该过程是非常耗性能的操作,所以能提前预知HashMap中元素的个数,在新建时直接指定HashMap容量,就能有效地提高HashMap的性能。
(2)精妙的rehash
- 介绍:rehash的过程就是计算数组下标,计算过程为(n-1)&hash
- 优势:不需要重新hash,节省了重新计算hashCode的时间,还是保持hashCode的随机性,分散冲突
- 举例:假定容量变更后n=16,则n-1转为二进制为1111,此容量HashMap的数组下标为[0,15],此时用(n-1)&hash就可以得到0~15之间的任意值,从而计算出来新的位置
- 因为每次扩容都是翻倍,也就是在计算下标时,多计算hash的一个bit位
- 结果:节点要么在原来的位置,要么在"原位置+旧容量"的位置
2、二次扰动
(1)过程说明:将得到的hashCode转化为32位二进制,高16bit不变,用低16bit和高16bit做异或操作
(2)上图参数:
- h:哈希值;
- hash:高16bit和低16bit异或;
- n:HashMap数组长度,每次扩容后翻倍,向高位进一位即可
(3)二次扰动原因:防止数组很小且hashCode高位变化大,低位变化小的情况,将高位全部利用上,降低哈希冲突概率
(4)为什么使用异或操作:与“&”和“|”操作相比,保证hashCode只要有一位发生变化,计算值就会发生改变,尽可能减小碰撞。



