美文网首页
JDK 1.8下对HashMap的理解

JDK 1.8下对HashMap的理解

作者: 贰shu | 来源:发表于2019-12-31 16:12 被阅读0次

---------[ HahsMap ]-------------

JDK 1.8

1、K、V 可以为 null,非线程安全

2、实现原理

  • 数组(Node[] table) + 链表(Node) + 红黑树(TreeNode)
  • HashMap使用 Node[] table 数组存放 Node<K, V>节点;
  • 初始化HashMap的时候,table容量默认为16 (1 << 4);
  • Key hash值相同的节点,存入table相同位置,以链表结构存储(Node就是链表结构),新值存放在链表末尾;
  • 当某个节点的链表长度超过8时,会转为红黑树TreeNode(若table长度未超过最小阀值(MIN_TREEIFY_CAPACITY = 64)时,优先扩容);

读取时:
首先计算所在数组的位置 index = hash(K) & (n - 1),然后再遍历链表或红黑树,取K相同得节点

3、何时触发扩容?扩容时,是否需要重新计算hash?

    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    static final float DEFAULT_LOAD_FACTOR = 0.75f;     // 负载因子
    /**
     * 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;
    
    if (++size > threshold) resize();
    // 双倍扩容 oldCap << 1
    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;
        }
    }

扩容时,不会重新计算key的hash值,但是会重新计算该节点在数组中的位置,并放入新的 Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];

4、什么时候由链表转为红黑树?

链表长度超过8,并且数组table容量超过64,若未超过64,则会触发数组扩容,直到容量大于64,才会转为红黑树

5、HashMap容量为什么是2的幂次方?

put(K key, V value) 操作时,存放的位置是按照key的hash值 与 (table的容量-1) 按位与(&)计算出来的

// index 一定小于 table的容量(2^n)
index = (2^n - 1) & hash(K)
/**
 * e.hash & 2^n == 0,迁移至新数组时,index = j
 * e.hash & 2^n != 0,迁移至新数组时,index = j + oldCap
 * 二进制 & 按位与 运算结果
 *  111 1000 1111   111 1000 1111
 * 1111 1111 1111   111  111  111
 * --------------  --------------
 * 0111 1000 1111   111 0000 0111
 */

6、key的hash计算方法

(key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16)

7、源码解读

    /**
     * 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;
        // tab为空
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // i位置的节点为空,则添加一个新节点p
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // key的hash相同,key也相同,则节点替换
            if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // p为TreeNode,红黑树
            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;
                    }
                    // 判断新节点hash、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;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
    

扩容

    /**
     * 初始化 或 扩容
     * Initializes or doubles table size.  
     * If null, allocates in accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, 
     * the elements from each bin must either stay at same index, 
     * or move with a power of two offset in the new table.
     *
     * @return the table
     */
    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;
            }
            // 双倍扩容  double threshold
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; 
        }
        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);
        }
        
        // 扩容后,新建数组,并赋值给table,迁移节点 至新数组
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            // 遍历旧数组oldTab
            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;
                            /**
                             * e.hash & 2^n == 0,迁移至新数组时,index = j
                             * e.hash & 2^n != 0,迁移至新数组时,index = j + oldCap
                             * 二进制 & 按位与 运算结果
                             *  111 1000 1111   111 1000 1111
                             * 1111 1111 1111   111  111  111
                             * --------------  --------------
                             * 0111 1000 1111   111 0000 0111
                             */
                            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;
    }

链表转化为红黑树

    /**
     * 树化桶 - 将链表转为红黑树
     * 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;
        // 如果table为空、或者tab.length < 树化的阀值,则扩容
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        // index 为根据该hash值计算出来的table数组中存放的位置
        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);
        }

相关文章

网友评论

      本文标题:JDK 1.8下对HashMap的理解

      本文链接:https://www.haomeiwen.com/subject/crzboctx.html