当前位置: 首页 > news >正文

HasMap源码学习(持续更新)

源码解析

属性

    /**
     * The default initial capacity - MUST be a power of two.
     */
     // 默认初始容量
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The load factor used when none specified in constructor.
     */
     // 默认加载因子,扩容的阈值
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

	// HasMap存储数据的数组
    transient Node<K,V>[] table;

   	static class Node<K,V> implements Map.Entry<K,V> {
   		// 哈希值 计算数组中的索引位置
        final int hash;
        final K key;
        V value;
        // 用于联表和红黑树
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }
    
    // 当前容量
 	transient int size;

构造方法

    /**
     * Constructs an empty {@code HashMap} with the default initial capacity
     * (16) and the default load factor (0.75).
     */
     // 懒惰加载,创建时没有初始化数组
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

put方法

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}.
     *         (A {@code null} return can also indicate that the map
     *         previously associated {@code null} with {@code key}.)
     */
     // put方法
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * 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为null,调用resize方法初始化容量
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 如果插入的key对应的table上没有node,则直接创建新的node    
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 已经根据hash找到了当前table数组的索引位置p,判断p的头节点的key是否和这一次put的key相等,就会直接覆盖(源码654行e.value = value;)
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 如果key不相等,判断是否是红黑树,是就走红黑树的添加逻辑    
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            // 如果key不相等,且不是红黑树,走链表的添加逻辑 
            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;
                    }
                    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;
            }
        }
        // 容量加一,如果超过了threshold=数组长度*加载因子,触发扩容
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

相关文章:

  • 割平面法的理解
  • 销售易CRM:用户体验与实际应用深度分析
  • Uniapp项目运行到微信小程序、H5、APP等多个平台教程
  • 【音视频】ffmpeg命令参数说明
  • 【一文学会 HTML5】
  • 洛谷 P1194 买礼物 最小生成树--但有小坑
  • ESP32S3N16R8驱动ST7701S屏幕(vscode+PlatfoemIO)
  • 【清华大学】实用DeepSeek赋能家庭教育 56页PDF文档完整版
  • selenium库
  • 记录一次mysql全文索引不生效
  • C#中的委托是什么?事件是不是一种委托?委托与事件的区别?
  • SpireCV荣获Gitee 最有价值开源项目称号
  • 鸿蒙跨平台框架ArkUI-X
  • Android 屏幕适配 Tips
  • 单片机如何用C语言重写vfprintf
  • npm 执行安装报错
  • Final Cut Pro X for Mac fcpx音视频剪辑编辑
  • 项目设计之用户注册与登录
  • Unity HDR颜色、基础颜色、强度强度、HDR面板Intensity之间的相互转换
  • UDP协议 TCP协议(格式 超时重传 滑动窗口 拥塞控制...)
  • 网站开发贴吧/行业关键词分类
  • 做网站市场报价步登顶/搜索百度下载安装
  • 完善网站建设的目的是/苏州百度 seo
  • idea 做网站登录/夸克搜索引擎入口
  • 樟木头仿做网站/发布悬赏任务的推广平台
  • 网站打不开原因检测/爱情链接