HashMap源码

本文详细剖析了HashMap的内部结构,包括其哈希算法、扰动函数、链表与红黑树转换机制,以及扩容策略。同时,文章介绍了HashMap的构造方法、常量与变量设置,并深入探讨了put操作的具体流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HashMap

单个数组元素 桶 —存链表/红黑树
数组 table
在这里插入图片描述

一、结构基础
1.1哈希
  • 先计算key的hashCode
  • 再使用扰动函数(减少哈希碰撞几率 )得到hash值
  • (n-1)&hash 当前元素应在的位置
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
1.2 transient Set<Map.Entry<K,V>> entrySet 包含全部键值对的集合
1.3 transient Node<K,V>[] table;
1.4 Node
  • K key
  • V value
  • Node<K,V> nextNode
    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;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }
二、常量&变量
  • 默认初始容量 2^4 ==> 16
  • 最大容量 2^30
  • 默认加载因子 0.75
  • 树化阈值 当链表长度>=8时(桶上元素),链表转化为红黑树
  • 树退化阈值 当树大小<=6时(桶上元素),树退化为链表
  • 最小树化容量 64 这里指的是数组长度 小于64扩容 大于等于64树化
    当链表长度>=8,且table.length(数组长度)>=64时,才会树化
    在这里插入图片描述
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    static final int MAXIMUM_CAPACITY = 1 << 30;
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    static final int TREEIFY_THRESHOLD = 8;
    static final int UNTREEIFY_THRESHOLD = 6;
    static final int MIN_TREEIFY_CAPACITY = 64;
  • size hashMap中键值对(映射)的数量
    /**
     * The number of key-value mappings contained in this map.
     */
    transient int size;
  • threshold
    /**
     * The next size value at which to resize (capacity * load factor).
     */
    int threshold;

在这里插入图片描述在这里插入图片描述

  • modCount
    修改次数 (hashMap线程不安全,该值相当于一个标志,其他线程修改了Map的结构,这个值就会变化,遍历的时候modCount与预期值不符合,就会报错)
    modCount就是HashMap进行结构调整的次数,结构调整就是对键值对数量的改变或者用其他方式改变HashMap的内部结构(比如rehash)。这个实例域用于在属于“HashMap Fail-Fast”的集合视图上生成迭代器。
    /**
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     */
    transient int modCount;
        public final void forEach(Consumer<? super K> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
三、构造方法

3.1 带初始容量和加载因子
进行边界情况判断
计算threshold(返回>=给定容量,最小的 ,2的n次方)

 public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
       /**
     * Returns a power of two size for the given target capacity.
     * 返回大于capacity的 最小的 2的n次方
     */
        this.threshold = tableSizeFor(initialCapacity);
    }

3.2 带初始容量

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

3.3 无参构造

 public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

3.4 以其他Map为参数

    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }
putMapEntries(基础还是putVal)
  • 用于构造方法
  • 用于putAll
  public void putAll(Map<? extends K, ? extends V> m) {
        putMapEntries(m, true);
    }
  final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }
四、扩容机制
  • 新增元素 旧table为空
  • 新增元素 旧map.size()>threshold
4.1 先获取 新容量capacity 新阈值threshold
  • 如果之前是非空talbe,新容量为旧容量乘以2
  • 如果之前是空table,旧阈值不为0,新容量为旧阈值oldThreshold (前两个有参构造方法,但是初始容量设置为0,threshold通过tableSizeFor计算)
    • 如果之前是空table,旧阈值为0,新容量16,新阈值都是用默认值16*0.75(无参构造方法,直接用默认值)
  • 新阈值 = 新容量 × 加载因子(超过Max_Capacity 使用 Max_Value)
4.2 重新计算元素在新数组中的位置,然后挂结点
  • 树分裂
  • 链表
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
        // 如果大于最大容量 将threshold设置为最大整数(不会再resize) 不再扩容 
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 如果没有超过最大值 newCap = oldCap*2 
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                     // 扩容阈值 乘 2
                newThr = oldThr << 1; // double threshold
        }
        // 如果旧Cap=0 只带容量的构造方法(Cap=0),或双参(Cap=) , 新容量为旧threshold
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults 
        // 初始容量=0 threshold=0 无参构造方法 
        // 容量设为默认 16 
        // 阈值 默认 12  16X0.75
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 计算新的 threshold (新容量×加载因子 再进行一系列判断)
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        // 至此 各种属性大小已确定 newCap  newThreshold
        if (oldTab != null) {
        // 重新计算元素在新数组的位置 并填进去
        // 遍历旧的Map 将旧bucket 转移到 新 bucket 
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                // 原位置置空 元素都保存在e中
                    oldTab[j] = null;
                    // 遍历e (链表/红黑树)
                    if (e.next == null)
                    // 计算新的位置 然后挂上e
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                    // 如果e是树 要拆分 
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                    // e是链表
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
五、其他方法

5.1 新增 单个元素

  • 先判断原table 如果是空 resize()
    • 再判断计算后 结点位置table[i] 是否有元素 没有直接添加
      • 如果有元素 再判断key是否相同,相同进行值覆盖
        • key不相同,再判断table[i]是树 还是链表 是树直接按照树的方式挂结点
          • 如果是链表,还要判断加上这个结点会不会到达阈值,如果会 树化
            • 如果不会,直接在链表尾部加上新结点(遍历到尾部过程中,如果发现相同的key,进行值覆盖) JDK1.7 是在头部插入新结点
              • 最后还要判断size是否大于threshold ,如果大于,resize()
  public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
 public class A {
	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[] 是空的 
		if ((tab = table) == null || (n = tab.length) == 0)
			n = (tab = resize()).length;
	    // table[] 不是空 且 目标位置没有元素 直接挂上结点
		if ((p = tab[i = (n - 1) & hash]) == null)
			tab[i] = newNode(hash, key, value, null);
		// 该位置上已经有元素
		else {
			Node<K, V> e;
			K k;
			// key值相等 直接覆盖旧值
			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);
				// 否 找到链表的尾部
			else {
				for (int binCount = 0;; ++binCount) {
					if ((e = p.next) == null) {
					// 挂上新结点
						p.next = newNode(hash, key, value, null);
						// 0---7 达到阈值 树化 链表长到8-->红黑树
						if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
							treeifyBin(tab, hash);
						break;
					}
					// 与链表元素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;
		// 先挂结点 再size+1 size>threshold resize
		if (++size > threshold)
			resize();
		afterNodeInsertion(evict);
		return null;
	}
}

5.2 TreeifyBin 树化

 /**
     * Replaces all linked nodes in bin at index for given hash unless
     * table is too small, in which case resizes instead.
     */
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        // 如果table是空或者table的length(数组长度)<树化阈值 resize()扩容
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }
### 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、付费专栏及课程。

余额充值