HashMap之Put方法解读

HashMap底层是使用Entry对象数组存储的,而Entry是一个单项的链表或者是红黑树。
下面是对HashMap的put源码的解读

  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)
            n = (tab = resize()).length;

     /*根据 hash 值确定节点在数组中的插入位置,若此位置没有元素则进行插入,
     注意确定插入位置所用的计算方法为 (n - 1) & hashCode(key),由于n 
     一定是2的幂次,这个操作相当于hash % n */

        //如果index位置对应的没有key
        if ((p = tab[i = (n - 1) & hash]) == null) 
            tab[i] = newNode(hash, key, value, null); //就创建一个新节点
        else {//待插入的位置存在元素
            Node<K,V> e; K k;
            //比较原来元素的hash值和key值
            if (p.hash == hash &&
               ((k = p.key) == key || (key != null && key.equals(k))))
                //如果key和hash值相等,不操作
                e = p;
            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);
                        //如果链表个数超过6就将链表结构转为红黑树结构
                        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;
                }
            }
            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;
    }

在HashMap中使用对象作为key的情况,都说用可变对象是很危险的,顺便就把HashMap中的Put看了一遍

猜你喜欢

转载自blog.csdn.net/weijifeng_/article/details/80007693
今日推荐