HashMap 1.8 源码分析

理解

  • HashMap 结构可以看出是由数组+链表+红黑树组成的。

put 方法

《HashMap 1.8 源码分析》

  • 1 首先判断table是否为0或Null,那么就resize()扩容一下。
  • 2 根据hash计算出在这个table数组的位置。如果当前位置还没有链表,那么就直接插入一个结点。如果已经存在节点了。那么继续判断。
  • 3 首先第一步判断:链表的第一个节点key是否跟要插入的节点相同。
  • 4 这一步判断链表是否是红黑树,如果是红黑树则进入红黑树的插入。
  • 5 遍历链表,将每个节点与插入的节点进行毕竟,如果有相同的就退出。如果没有,那么就建立一个新的节点。
  • 6 这一步是存在相同key而发生的。是替换掉旧的值。
  • 如果节点的个数大于容纳个数,那么就扩容。
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //1
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //2
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            //3 
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //4 
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //5
            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;
                }
            }
            //6 
            if (e != null) { 
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //7 
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

get 方法

  • 1 根据目标Key的hash,计算出数组的索引。
  • 2 首先判断第一个节点是否是目标key,如果是则立即返回。
  • 3 判断该链表是否是红黑树。
  • 4 如果不是红黑树,那么遍历链表,获取到目标key的node 节点。
  • 5 如果该节点不为空,则返回zhi
public V get(Object key) {
        Node<K,V> e;
        //5
        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;
        //1
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //2
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                 //3
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                    //4
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

resize方法

总体思路是:先判断能否扩容,如果可以,那么就扩大2倍。如果不能,那么就返回。如果扩容成功那么就需要对node节点重新分配。jdk1.8做的优化是:key对应的哈希与高位运算结果,看最高位bit,如果是0则位置不换。如果是1则在原位置再移动2次幂的位置。
– 1 先判断是否能扩容。
– 2 开始进行Node节点重新分配。先重新建立一个数组。
– 3 开始遍历旧的数组。
– 4 如果在该数组索引下有节点。
– 5 先将旧数组索引设置成Null,等cg回收
– 6 判断该Node节点有没有成链,如果是单一节点。直接计算新的索引存放
– 7 判断该node节点是否是红黑树。如果是红黑树那就进行split()方法。
– 8 经过两次判断,可以确定该node节点是链表。
– 9 新键两个Node节点,相当于要建立两个链表,一个链表是继续存放在原本的数组索引下,一个是存放在新的数组索引下
– 10 判断Bit位是否为0
– 11 一个链表放在原本的数组索引位置
– 12 另一个链表放在原索引位置+原容量

 final Node<K,V>[] resize() {
         //1
        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;
            }
            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);
        }
        threshold = newThr;
        //2
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            //3 
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                //4
                if ((e = oldTab[j]) != null) {
                    //5
                    oldTab[j] = null;
                    //6
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    //7
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                     //8
                    else { // preserve order
                        //9
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            // 10 
                            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);
                        //11
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        /12
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
    原文作者:给我丶鼓励
    原文地址: https://blog.csdn.net/GG_and_DD/article/details/80438658
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞