JDK1.8 HashMap链表长度大于8转为红黑树

——浅薄月季频出镜,纯情芦荟慎开花。愿祖国早日战胜疫情!中国加油!武汉加油!

一 JDK1.8 HashMap源码

/**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    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;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
/**
     * 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) // 当数组长度 >= 64 时
            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);
        }
    }

1. 当 binCount >= 7 时,表示当前数组节点下的链表长度已经达到至少8个了,这时就需要将链表转为红黑树存储。

二 为什么当链表长度为8时转换

1. 第一个原因:

        

        DEFAULT_INITIAL_CAPACITY = 1 << 4 数组默认长度为16

        DEFAULT_LOAD_FACTOR = 0.75f 扩容因子为0.75

        即,当数组存储元素 >= 16 * 0.75 = 12 时,就需要开始扩容。

        而,根据 hash()函数计算出的下标,导致在一个 table[i] 桶 位置出现个数的概率为:

同一位置出现次数概率
0    0.60653066
1    0.30326533
2    0.07581633
3    0.01263606
4    0.00157952
5    0.00015795
6    0.00001316
7    0.00000094
8    0.00000006

        符合泊松分布,当一个位置出现 8 个元素的时候,就被认为 hash()函数设计的不好。就会自动转为红黑树,提高性能。

2.第二个原因:

        对比 链表 和 红黑树 的区别:

        链表 

    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
}

        红黑树

    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
}

        在空间复杂度上: 红黑树 是 链表的 2 倍。(因为出去其他多余信息,链表只有一个 next 属性,而红黑树有 left,right 两个属性)。

        在时间复杂度上:

节点个数链表时间复杂度红黑树时间复杂度链表时间复杂度结合空间复杂度红黑树时间复杂度结合空间复杂度
11112
22224
33234
44346
55356
66468
77478
88488
99498

 

        红黑树时间复杂度(如下图)

        

        前提:红黑树 的空间复杂度是 链表 的 2 倍。         

        说明:

        1. 当 table[i] 上的链表个数 < 8 时,空间复杂度 结合 时间复杂度 链表 的效率 优于 红黑树。

        2. 当个数 = 8 时,链表 和 红黑树 的效率一样。

        3. 当个数 > 8 时,红黑树 的效率 优于 链表。

三 结论

        所以当 链表 中的元素个数 > 8 之后,还需要判断当前数组的长度。如果数组长度 < 64 时,此时并不会转换为 红黑树,而是扩容。只有当 链表 中的元素个数 > 8,并且 数组的长度 >= 64 时才会将链表转为红黑树。

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值