前两篇文章我们介绍了HashMap的内部结构以及哈希冲突发生时链表的生成过程。
这篇文章给大家解释HashMap的内部的红黑树是怎么生成的。
代码案例
public static void part3() {
// 步骤一, 初始化代码,插入64条数据
Map<Integer, Integer> map = new HashMap<>(128);
for (int i = 0; i < 64; i++) {
map.put(i, i);
}
// 步骤二,插入特定hash值,触发hash碰撞,生成红黑树
int i = 1;
for (; i <= 8; i++) {
map.put(128 * i, 128 * i);
}
}
执行完上述代码后HashMap的内部结构变化如图:
代码解释
- 步骤一执行完后,HashMap内部会生成一个长度为128的数组,数组的前64位(0~63)的Node对象的key-value值和数组index值相同(HashMap内key-value键值对数量为64)。
- 步骤二执行完后,HashMap的内部数组index为0的节点变成了一颗红黑树。
- 为什么要执行步骤一呢?
当内部数组tab的长度超过MIN_TREEIFY_CAPACITY时,才会执行红黑树生成逻辑。
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
*/
static final int MIN_TREEIFY_CAPACITY = 64;
HashMap是通过tab[i = (n - 1) & hash]来定位新的key-value键值对要插入到内部数组的哪个位置的,这时n为内部数组长度128,n-1对应到二进制为0111 1111,Integer的hashcode值就是它本身的int值,这时hashcode就发生冲突了,都插入到了index为0的位置,组成了一个链表:
0111 1111&0000 0000=0
0111 1111&1000 0000(128)=0
0001 1111&0001 0000 0000(256)=0
...
下面为HashMap部分源码,当哈希冲突的键个数超过TREEIFY_THRESHOLD的值(8)时,HashMap会把链表转换成红黑树:
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
红黑树是一种平衡二叉树,相关原理可以查阅下百度百科等平台,下面是HashMap红黑树相关的部分源码
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> 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);
}
}
这篇文章就分享到这里,后续还有HashMap其他文章会陆续发布。
大家如果有问题欢迎在评论区留言一起探讨,同时也可以关注收藏“小西学JAVA”和同名公众号,有文章更新会及时收到通知。