美文网首页
HashMap源码分析

HashMap源码分析

作者: 一人_e0fb | 来源:发表于2020-07-21 23:04 被阅读0次

    本文基于jdk1.8进行解读

    其实HashMap最主要的几个方法分别是
    • put(设置值)
    • get(获取值)
    • initTable(初始化hash表)
    • resize(扩容)
    • treeifyBin(树化)
    • untreeify(退化为链表)

    • put方法
    public V put(K key, V value) {
            return putVal(hash(key), key, value, false, true);
        }
    
    static final int hash(Object key) {
            int h;
            // 高16位与低16位做异或,防止map容量较小时,hash冲突概率较大
            // 假设我map容量为16,取模后都会剩下低四位,那只要我低四位相同就一定会冲突
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        }
    
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                       boolean evict) {
            Node<K,V>[] tab; Node<K,V> p; int n, i;
            // 如果hash表未初始化
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
    
            // (n - 1) & hash 是对hash取模tab.length(map的容量),这也是HashMap大小一定是2的幂的原因
            // 如果hash取模后,通过索引在hash表中获取数据为空
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
            // 如果hash取模后,通过索引在hash表中获取数据不为空
            else {
                Node<K,V> e; K k;
                // p是第一步的if里面获取到的node,这里判断hash与key是否相同,因为key可为null,所以key对比有两步
                if (p.hash == hash &&
                        ((k = p.key) == key || (key != null && key.equals(k))))
                    e = p;
                // 其实第一步判断了是否相同,后面就是树和链表的处理逻辑了
                // 获取的node为树
                else if (p instanceof TreeNode)
                    e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                // 获取到node为普通node
                else {
                    // 遍历node链表,binCount为链表长度-1
                    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;
                        }
                        // 有相同的key
                        if (e.hash == hash &&
                                ((k = e.key) == key || (key != null && key.equals(k))))
                            break;
                        p = e;
                    }
                }
                // 在前面判断hash和key是否相同的逻辑中,e = p | 在node链表遍历过程中, e = p.next
                // 即e是与要设置的值key相同的节点
                if (e != null) { // existing mapping for key
                    V oldValue = e.value;
                    // 这里替换node的value,onlyIfAbsent这个字段是是否值不存在时才设置
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    // 值替换后续处理,主要是LinkedHashMap使用
                    afterNodeAccess(e);
                    return oldValue;
                }
            }
            ++modCount;
            // 如果node增加后大小大于阈值,扩容
            if (++size > threshold)
                resize();
            // node 插入后处理,主要是LinkedHashMap使用
            afterNodeInsertion(evict);
            return null;
        }
    

    • get方法
    public V get(Object key) {
            Node<K,V> e;
            return (e = getNode(hash(key), key)) == null ? null : e.value;
        }
    
    final Node<K,V> getNode(int hash, Object key) {
            Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
            // table 已初始化
            if ((tab = table) != null && (n = tab.length) > 0 &&
                    (first = tab[(n - 1) & hash]) != null) {
                // 检查头节点是否为对应的数据
                if (first.hash == hash && 
                        ((k = first.key) == key || (key != null && key.equals(k))))
                    return first;
                // 非头节点数据情况
                if ((e = first.next) != null) {
                    // 是否为红黑树
                    if (first instanceof TreeNode)
                        return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                    // 遍历链表
                    do {
                        if (e.hash == hash &&
                                ((k = e.key) == key || (key != null && key.equals(k))))
                            return e;
                    } while ((e = e.next) != null);
                }
            }
            // table 为空返回null
            return null;
        }
    

    • initTable
    • resize
      hashMap中initTable使用的直接是resize方法,所以一起看
     final Node<K,V>[] resize() {
            // 拿到整个hash表
            Node<K,V>[] oldTab = table;
            // hash表如果未初始化,oldCap=0
            int oldCap = (oldTab == null) ? 0 : oldTab.length;
            int oldThr = threshold;
            int newCap, newThr = 0;
    
            // hash表已初始化
            if (oldCap > 0) {
                // 已经是最大容量了
                if (oldCap >= MAXIMUM_CAPACITY) {
                    threshold = Integer.MAX_VALUE;
                    return oldTab;
                }
                // 扩容也没有达到最大容量的情况下,capacity和threshold都左移一位,相当于乘2
                else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                        oldCap >= DEFAULT_INITIAL_CAPACITY)
                    newThr = oldThr << 1; // double threshold
            }
            // 未初始化,使用了带参构造,oldThr = threshold = tableSizeFor(initialCapacity)
            else if (oldThr > 0) // initial capacity was placed in threshold
                newCap = oldThr;
            // 未初始化,使用了无参构造
            else {               // zero initial threshold signifies using defaults
                newCap = DEFAULT_INITIAL_CAPACITY; // 16
                newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 16 * 0.75 = 12
            }
    
            // 带参构造未初始化
            // 扩容后会超过 MAXIMUM_CAPACITY
            if (newThr == 0) {
                float ft = (float)newCap * loadFactor;
                newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                        (int)ft : Integer.MAX_VALUE);
            }
            threshold = newThr;
            @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
            table = newTab;
            // 将node塞入新表
            if (oldTab != null) {
                for (int j = 0; j < oldCap; ++j) {
                    Node<K,V> e;
                    if ((e = oldTab[j]) != null) {
                        oldTab[j] = null;
                        // 单一的node节点
                        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;
                                // 扩容后槽未变
                                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;
        }
    

    • treeifyBin
    final void treeifyBin(Node<K,V>[] tab, int hash) {
            int n, index; Node<K,V> e;
            // 如果hash表未初始化或表大小小于转换树的最小大小
            // 这里明显tab == null的判断只是防止空指针,真正目的在于判断map的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;
                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);
            }
        }
    

    • untreeify
    final Node<K,V> untreeify(HashMap<K,V> map) {
                Node<K,V> hd = null, tl = null;
                for (Node<K,V> q = this; q != null; q = q.next) {
                    Node<K,V> p = map.replacementNode(q, null);
                    if (tl == null)
                        hd = p;
                    else
                        tl.next = p;
                    tl = p;
                }
                return hd;
            }
    

    相关文章

      网友评论

          本文标题:HashMap源码分析

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