HashMap源码之put操作

156 阅读2分钟
HashMap数据结构

image.png

新增时步骤如下:
  • 新增键值对时,首先会判断table即数组是否为空,如果为空,使用resize方法初始化。

  • 如果table不为空,使用hash值计算在table中的索引值

    • 如果当前索引没有值,则将新的键值对放在此处

    • 如果当前所引处有值,则存在冲突

      • 如果当前索引处的值的hash值以及key值和新插入的键值对相同,则用新的键值对替换旧的键值对的值
      • 如果当前索引处的键值对是树结构,调用在红黑树中新增节点的方法
      • 如果当前索引处的键值对是链表结构,则遍历链表,将新的键值对存入该链表中
​
     * Implements Map.put and related methods.
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果table为空,使用resize进行初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //根据hash值算出在数组中的位置,如果在此位置恰好没有找到值,直接在对应的位置赋值
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            //如果在对应的位置已经存在值,那么应该进行冲突处理。
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                //如果在该位置已经存在的键值对和将要存储的键值对的key值相等,那么用新值替换旧值
                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);
                        //如果当前链表中的节点数量超过链表结构阈值,将链表结构转换为红黑树结构
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果当前节点的hash和key 与将要存储的键值对相同,用新的键值对替换旧的键值对
                    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;
    }