HashMap 源码

1.8 阈值

resize()函数
threshold = newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);  
16*0.75 = 12

 

JDK1.7 put()

    public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            //初始化大小 根据要创建的数组大小计算出2次幂最接近的数字
            inflateTable(threshold);
        }
        if (key == null)
            //key为空的话直接放到数组[0]
            return putForNullKey(value);
        int hash = hash(key);//计算hash值 高位右移 使得高位参与hash运算 优化散列效果
        int i = indexFor(hash, table.length);//根据hash值和数组长度算出脚标 h & (length-1);
        //遍历数组[i]为头结点的链表
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            //找到key相同的元素的话 覆盖value 并且返回被覆盖的value
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        //没找到节点的话 添加新节点
        addEntry(hash, key, value, i);
        return null;
    }

JDK1.7扩容 转移数据

    /**
     * Transfers all entries from current table to newTable.
     */
    void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        //遍历数组
        for (Entry<K,V> e : table) {
            //遍历链表
            while(null != e) {
                //保存next元素
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                int i = indexFor(e.hash, newCapacity);

                //头插法 将新元素插入到新的table 并把新table原来的元素插入到后面
                e.next = newTable[i];
                //新元素作为数组的头结点
                newTable[i] = e;
                e = next;
            }
        }
    }

JDK1.8 put()

    /**
     * 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;
        if ((tab = table) == null || (n = tab.length) == 0)
            //创建数组
            n = (tab = resize()).length;
        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))))
                e = p;//数组第一个元素如果hash和key一样的话直接覆盖value
            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);
                        //深度达到8时候转化成红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
             --------final void treeifyBin(Node<K,V>[] tab, int hash) {
             --------int n, index; Node<K,V> e;
             --------数组长度小于64的话会进行扩容而不是树化 而是进行扩容
             --------if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
             -------resize();
                    

                        break;
                    }
                    //发现hash和key相同的话 退出循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    //指针指向下一个节点
                    p = e;
                }
            }
            //找到了key相等的直节点 覆盖新值 返回旧值
            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;
    }

https://www.bilibili.com/video/av79122849

https://www.bilibili.com/video/av82235643

### Java HashMap 源码解析 Java 的 `HashMap` 是基于哈希表实现的一种数据结构,它允许存储键值对 (Key-Value Pair),并支持快速的插入、删除和查找操作。以下是关于其内部工作原理的一些关键点: #### 数据结构设计 `HashMap` 使用数组加链表(或者红黑树)的方式来解决哈希冲突问题。具体来说: - **数组**:用于存储桶 (Bucket)。 - **链表/红黑树**:当多个键映射到同一个桶时,这些键会以链表的形式存储;如果链表长度超过一定阈值,则转换为红黑树。 这种设计使得在大多数情况下可以保持 O(1) 时间复杂度的操作性能[^3]。 #### 主要成员变量 以下是 `HashMap` 类中几个重要的字段及其作用: - `transient Node<K,V>[] table`: 存储实际数据的数组。 - `final float loadFactor`: 负载因子,默认值为 0.75,表示何时需要扩容。 - `int threshold`: 当前容量乘以负载因子的结果,决定了什么时候触发重新调整大小的动作。 - `static final int TREEIFY_THRESHOLD = 8`: 如果某个桶上的节点数量达到此数值,则该链表会被转化为一棵平衡二叉搜索树。 #### 核心方法剖析 1. **put 方法** 插入新元素时,先计算 key 对应 hash 值的位置 index。如果目标位置为空则直接放置新的 Entry;否则遍历已有条目寻找相同 Key 或者处理碰撞情况。 2. **get 方法** 获取指定 key 所关联 value 过程相对简单明了——依据同样的逻辑定位至相应索引处再逐一匹配直至找到完全一致项为止即可返回对应 Value 值。 ```java // 示例代码展示 put 和 get 的基本流程 public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } 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) tab[i] = newNode(hash, key, value, null); else { ... } } ``` --- ### C++ Hashmap 实现原理 尽管标准库并没有提供名为 “hashmap” 的容器类型名称,但实际上我们可以利用 STL 提供的标准模板类 unordered_map 来完成类似功能开发任务需求[^2]。 #### 关键特性对比 | 特性 | std::unordered_map | |-----------------|-----------------------------------------| | 底层实现 | 开放寻址法 / 拉链法 | | 平均时间复杂度 | 查找、插入、删除均为 O(1) | 值得注意的是,在某些特定场景下由于存在大量重复 keys 导致频繁 rehashing 可能会使最坏情形退化成接近线性的表现效果。 --- ### Python Dict 内部结构 Python 字典 (`dict`) 同样采用了类似的哈希表机制作为基础构建单元之一[^4]。然而为了进一步优化空间利用率以及提升运行效率等方面考虑引入了一些额外改进措施比如紧凑型分配策略等等从而形成了独具特色的版本特点如下所示: - **动态增长**: 初始状态下仅占用少量内存区域随着不断新增项目逐步按需扩展规模直到满足当前所需为止. - **探查序列**: 解决冲突采用开放地址技术即一旦发现预设槽位已被占据便沿着固定模式继续向前探索下一个可用选项. 另外还有一点特别之处在于 Pyhton3.x 系列之后对其做了重要改动取消了原本单独维护顺序信息的做法转而依靠原生词条布局自然形成访问次序记录因此既保留原有优势又能节省更多资源消耗. ```python # 创建一个简单的字典对象演示如何运作 my_dict = {"apple": 1, "banana": 2, "cherry": 3} print(my_dict["banana"]) # 输出结果应该是 '2' ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值