zoukankan      html  css  js  c++  java
  • 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;
            if ((p = tab[i = (n - 1) & hash]) == null)        //i=(n-1)& hash  这一步确定了 键值对 要放入的桶的下标。如果这个桶是空的直接放入
                tab[i] = newNode(hash, key, value, null);
            else {
                Node<K,V> e; K k;                    //否则这个桶中有键值对 节点
                if (p.hash == hash &&                  //桶中 链表的第一个节点的hash 与传入的键值对的hash true不短路继续 比较 key的数值 也为true 这个时候 就把这个节点传给 e,并把 e中的值返回
                    ((k = p.key) == key || (key != null && key.equals(k))))
                    e = p;
                else if (p instanceof TreeNode)            //这个p 键值对链表是否属于 红黑树 ,属于按照红黑树的方式插入
                    e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                else {                           //传入的键值对的key 和链表的第一个节点不相等并且 p不是红黑树。
                    for (int binCount = 0; ; ++binCount) {
                        if ((e = p.next) == null) {          //判断第二个节点是否为null,为空直接插入,并退出循环。这个时候把会把正在判断的这个节点的值传给e作为返回值
                            p.next = newNode(hash, key, value, null);
                            if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                                treeifyBin(tab, hash);
                            break;
                        }
                        if (e.hash == hash &&            // 不为空进行判断,是否相等,如果key相等 直接退出循环,返回e
                            ((k = e.key) == key || (key != null && key.equals(k))))
                            break;
                        p = e;                    //不为空,判断key不相等,就把p下一一位。准备和下一个节点 循环
                    }
                }
                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;
        }
  • 相关阅读:
    Gitlab forbidden
    oracle查询directory_path
    oracle_backup
    oracle
    客户端读取图片文件
    Sql游标的使用
    Sql解锁 数据库死锁检测
    css3d总结
    Redis在Linux系统下的安装和启动
    Linux系统基本操作命令
  • 原文地址:https://www.cnblogs.com/xiaoeyu/p/10604450.html
Copyright © 2011-2022 走看看