源码解析之HashMap源码

关于HashMap的源码分析,网上已经有很多写的非常好的文章了,虽然多是基于java1.8版本以下的。Java1.8版本的HashMap源码做了些改进,理解起来更复杂点,但也不脱离其桶+链表或树的重心思想。下面贴出1.8代码的源码解析,至于更详细内容以后补充。另外补充一点大家看源码一定要看看源码开头的注释,它对我们理解源码有很大帮助。

本文代码解析围绕着 get和put操作进行。

    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;
        if ((tab = table) != null && (n = tab.length) > 0 &&
                (first = tab[(n - 1) & hash]) != null) {//判断table不为null,tab.len>0且hash不为0,因为tab.len永远为二次幂
            if (first.hash == hash && // always check first node//所以n-1的二进制永远是1111111……
                    ((k = first.key) == key || (key != null && key.equals(k))))//如果hash相同且key==或equals其中一个相等返回first
                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);
            }
        }
        return null;
    }
    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;
        if ((tab = table) == null || (n = tab.length) == 0)//还没初始resize()化,resize初始化大小
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)//数组上没有对应节点,p为对应bucket第一个节点
            tab[i] = newNode(hash, key, value, null);//直接数组赋值
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&       //如果传入节点与第一个节点相同key,e指向第一个节点
                    ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)//如果p是tree节点,e指向转型相同key的p
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {//与第一个节点没有相同key,也不是tree节点。顺着跟节点找到链表尾端看有没有相同key,没有创建新节点,有则p指向e(与传入节点相同的节点)
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {//e指向p.next,为null是创建新节点
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st//如果超过tree结构转型阈值,则转型
                            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  //如果e不为空,说明在链表中找到了相同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;
    }

resize()

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;//原数组odlcap长度
        int oldThr = threshold;/ /原阈值
        int newCap, newThr = 0;
        if (oldCap > 0) {//如果数组长度大于0
        if (oldCap >= MAXIMUM_CAPACITY) {//如果大于最大值,阈值提高,返回原数组
        threshold = Integer.MAX_VALUE;
        return oldTab;
        }
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&   //如果容量小于最大容量1/2,大于默认初始容量,容量加倍,新阈值=原阈值加倍。
        oldCap >= DEFAULT_INITIAL_CAPACITY)
        newThr = oldThr << 1; // double threshold
        }
        //如果数组长度不大于0,原阈值>0,新容量等于原阈值。(注意构造Hashmap设置初始容量时,阈值一定为大于等于且最接近初始容量的2的次幂
        else if (oldThr > 0) // initial capacity was placed in threshold
        newCap = oldThr;
        else {   //数组长度不大于0,构造时也没设初始容量。            // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;//容量为默认容量
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//新阈值=默认容量*默认负载因子
        }
        if (newThr == 0) {//数组没初始化,构造函数设了初始容量,会有阈值,阈值=原阈值*加载因子(同上,构造时阈值一定是2的次幂。)
        float ft = (float)newCap * loadFactor;//新容量*加载因子
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
        (int)ft : Integer.MAX_VALUE);//新阈值等于ft或Integer最大值
        }
        threshold = newThr;//阈值更改为新阈值
@SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
        for (int j = 0; j < oldCap; ++j) {
        Node<K,V> e;
        if ((e = oldTab[j]) != null) {//如果原数组某个位置有值
        oldTab[j] = null;//首先清零该值
        if (e.next == null)//如果只有单值,不是链表或tree
        newTab[e.hash & (newCap - 1)] = e;//新数组根据hash到指定位置添加该值
        else if (e instanceof TreeNode)//如果数组该位置上是tree节点,进行处理
        ((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 {//这段代码主要将原数组一个桶内的链表分为两个链表(根据而二进制hash高分位数值。)。
        next = e.next;
        if ((e.hash & oldCap) == 0) {//newCap等于oldcap*2,所以newcap在二进制中比oldcap高一位,所以hash与cap位运算时要考虑新增位上对应的hash
        if (loTail == null)//loHead指向该节点            //是0还是1,0保持oldcap上的位置,1则放入oldcap位置+oldcap大小
        loHead = e;                                     //的位置。
        else
        loTail.next = e;//将低链表的节点连起来
        loTail = e;
        }
        else {//如果高分位为1
        if (hiTail == null)//hiHead指向e
        hiHead = e;
        else
        hiTail.next = e;//将高链表的节点连起来
        hiTail = e;
        }
        } while ((e = next) != null);//当(e指向next)不为null时,
        if (loTail != null) {//将高分位0返回到原j位置中
        loTail.next = null;
        newTab[j] = loHead;
        }
        if (hiTail != null) {//将高分位为1的返回到j+oldcap位置中
        hiTail.next = null;
        newTab[j + oldCap] = hiHead;
        }
        }
        }
        }
        }
        return newTab;
        }

猜你喜欢

转载自www.cnblogs.com/llsblog/p/10630398.html