HashMap的put方法源码解析 JDK1.8加入红黑树

  //HashMap的put方法
 public V put(K key, V value) {
   //通过key计算出key 的hashCode,以便查找在数组中的位置。
    return putVal(hash(key), key, value, false, true);
}

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, i;
    //如果hashMap是null 或者 是空 则重构hashMap
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // 若hashcode指定位置未被占用 则直接将该键值对插入, 也就是找到bucket(桶)位置来储存Entry对象。(这里是数组形式存储)
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    // 发现hashCode位置存在Entry对象时 解决方法
    else {
        HashMap.Node<K,V> e; K k;
        // 使用equals比较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) {
                //循环链表,直到Entry.next 找不到下个Entry的索引退出循环
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    // 若此时链表内长度大于等于8 将链表转化为红黑树 并将节点插入
                    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;
            }
        }
        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;
}
发布了25 篇原创文章 · 获赞 4 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/liuhaiquan123521/article/details/89349769