天天看点

JDK1.8版本的集合框架源码解析篇:HashMap.put方法

首先贴上源码:

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) {
        //tab代表你的hashmap所有数据存储的数组,数组数量就是你初始化或者后续经过扩容的数量
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果你的hashmap是null则会进行初始化,默认是16个数组,n为16
        if ((tab = table) == null || (n = tab.length) == 0) 
            n = (tab = resize()).length;
           //通过16与hash进行按位与运算得到的就是你的数据需要存的链表
        if ((p = tab[i = (n - 1) & hash]) == null)//初始化p的值就是链表头部
            tab[i] = newNode(hash, key, value, null);//如果头部是空则直接设置为新元素,同时next指向为null
        else {
            Node<K,V> e; K k;
            //这步是比较头部元素与目标key是否相等,相等则获取旧值进行返回
            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) {//开启标志位循环8次后将链表改为树形结构
                    if ((e = p.next) == null) {
                    //判断元素的下一个值是否存在,不存在则添加到链表末尾
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // 转换树形结构
                            treeifyBin(tab, hash);//后续讲解
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;//如果链表内某个元素与key相同则进行替换操作
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;//进行替换操作,将node的value替换位新值即可
                afterNodeAccess(e);//空实现,用于linkedhashmap
                return oldValue; //返回旧值
            }
        }
        ++modCount;//fail-fast机制,防止遍历的时候出现增改删操作,造成数据不安全
        if (++size > threshold)
            resize();//如果当前数组数量超过设定的则进行扩容操作,后续讲解
        afterNodeInsertion(evict);//空实现,用于linkedhashmap
        return null; //如果不是替换则返回null
    }
    
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            TreeNode<K,V> root = (parent != null) ? root() : this;//从跟节点开始遍历,后面循环就变成根节点
            for (TreeNode<K,V> p = root;;) {//这个是为了获取map中的旧值,如果存在则进行更新替换,方法外面进行更新替换
                int dir, ph; K pk;
                if ((ph = p.hash) > h)//如果节点的hash大于目标hash则设置dir=-1,下面将会将p赋值为当前节点的左节点进行遍历
                    dir = -1;
                else if (ph < h)//如果节点的hash大于目标hash则设置dir=1,下面将会将p赋值为当前节点的右节点进行遍历
                    dir = 1;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;//key相等则直接返回,说明已经存在对应的key了所以在外面进行更新操作
                else if ((kc == null &&//到这边已经说明key不相等但是hash‘code相等
                          (kc = comparableClassFor(k)) == null) ||//如果不是comparable的子类
                         (dir = compareComparables(kc, k, pk)) == 0) {//或者作为comparable子类并且比较之后相等
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        //通过调用find方法尝试获取目标key,获取倒就返回,其中find方法内部也是一个循环,找到对应的key
                        if (((ch = p.left) != null &&
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    dir = tieBreakOrder(k, pk);//到这里还没有找到说明的确不存在key,那么就执行插入操作,这步判断是插入在左边还是右边
                }

                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {//到这里说明要进行插入操作,需要插入到当前对象的左边还是右边
                    Node<K,V> xpn = xp.next;//获取链表的next
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);//新建节点并且将当前节点的next节点作为新节点的prev节点
                    if (dir <= 0)
                        xp.left = x;//根据dir判断放置在左边还是右边
                    else
                        xp.right = x;
                    xp.next = x;//将next指向新节点
                    x.parent = x.prev = xp;//将新节点的父节点,prev设置为当前节
                    if (xpn != null)//如果这个树下存在节点则进行平衡操作
                        ((TreeNode<K,V>)xpn).prev = x;
                    moveRootToFront(tab, balanceInsertion(root, x));//将root节点挂到tab数组上并且重新平衡
                    return null;
                }
            }
        }
 //将链表转换为红黑树
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)//如果tab数组为空或者小于64则进行扩容,
        //没必要进行转换红黑树,将key分散到多个槽中
            resize();//后续讲解
        else if ((e = tab[index = (n - 1) & hash]) != null) {//通过数组数量与hash按位于计算定位目标槽,其中e为根节点
            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);//将双向链表组成红黑树
        }
    }
   //将双向链表组成红黑树
   final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null;//申明根节点
            for (TreeNode<K,V> x = this, next; x != null; x = next) {//这个遍历所有节点
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
                if (root == null) {//将当前节点设置为根节点,父节点设置为null
                    x.parent = null;
                    x.red = false;//作为黑树
                    root = x;
                }
                else {//到这里说明根节点已经存在
                    K k = x.key;
                    int h = x.hash;
                    Class<?> kc = null;
                    for (TreeNode<K,V> p = root;;) {//下面就是创建树分散在树的2侧,但是放在2测的节点也有可能是2测节点更深层次的节点
                        int dir, ph;
                        K pk = p.key;
                        if ((ph = p.hash) > h)
                            dir = -1;
                        else if (ph < h)
                            dir = 1;
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);

                        TreeNode<K,V> xp = p;
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {//到这里左右节点都是空说明是叶节点,已经确定具体位置了,设置左右值即可
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x;
                            else
                                xp.right = x;
                            root = balanceInsertion(root, x);//进行树的平衡操作
                            break;
                        }
                    }
                }
            }
            moveRootToFront(tab, root);
        }

//扩容
final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;//备份原tab数组
        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
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }//当前容量的2倍如果小于最大容量并且大于默认容量16则进行扩大为2倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // 到这里说明是初始化的时候设置的初始化容量和负载因子,它的值就是你设置的容量最接近的2的n次方的那个值,比如10,那么就是16,resize的话就把你的容量设置为16
            newCap = oldThr;
        else {               // 走到这里就是默认构造器,容量就是16,边界值就是16*0.75=12
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {//如果边界值是0则需要设置
        //首先是0代表老边界就是0又或者当前tab就是空
            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;
        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)
                        newTab[e.hash & (newCap - 1)] = e;//如果只有一个元素则直接把数据进行位于运算放入新槽
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);//如果是数则需要进行树的分割
                    else { //进行链表复制
                    //设置头尾
                        Node<K,V> loHead = null, loTail = null;//低位首尾节点
                        Node<K,V> hiHead = null, hiTail = null;//高位首尾节点
                        Node<K,V> next;
                        do {xi
                        //进入循环体
                            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;
    }
           

注意:jdk1.7版本,新加元素是添加到链表头部,1.8是链表尾部

继续阅读