我们常会说:“hashmap中,当链表的长度超过8,就会从链表转化为红黑树”。
其实,这不是完全正确的。正确的说法是,“hashmap中,当链表长度超过8,且table数组的长度不小于64时,链表会转化为红黑树”。
不信,我们来看看。首先,HashMap.class中存在这样一个参数:
static final int MIN_TREEIFY_CAPACITY = 64;
文档注释为: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.
注释大意说是:bins会转化为红黑树的最小的桶的大小。
我们再来看看将链表转化为红黑树的这个函数treeifyBin:
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// 当数组为null或者数组的长度小于MIN_TREEIFY_CAPACITY,也就是64的时候,调用扩容方法
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;