From 1458e0aefd6f254c4c9377994b3ec72c1ea6e0aa Mon Sep 17 00:00:00 2001 From: andyoung <1218853253@qq.com> Date: Wed, 26 Jul 2023 14:52:22 +0800 Subject: [PATCH] Update hashmap-source-code.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加HashMap示例,加深对HashMap理解 --- docs/java/collection/hashmap-source-code.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/java/collection/hashmap-source-code.md b/docs/java/collection/hashmap-source-code.md index 8877a451..8c165756 100644 --- a/docs/java/collection/hashmap-source-code.md +++ b/docs/java/collection/hashmap-source-code.md @@ -113,6 +113,24 @@ public class HashMap extends AbstractMap implements Map, Cloneabl **threshold = capacity \* loadFactor**,**当 Size>threshold**的时候,那么就要考虑对数组的扩增了,也就是说,这个的意思就是 **衡量数组是否需要扩增的一个标准**。 +### 示例 + +`Map map = new HashMap<>();` + +- 刚初始化情况下,`table`为空,`threshold = 0`,`size=0`(size 为实际存储数据大小) + +- 当调用`put`方法时,会调用 `resize()` 方法扩容,库容到 table 大小为 16 `threshold = (int)(*DEFAULT_LOAD_FACTOR* * *DEFAULT_INITIAL_CAPACITY*)` = 16 x 0.75 = 12 + +- 是否要扩容判断 + + 调用 `put`方法 -> `putVal` 添加完后会进行扩容校验 + + ``` + ++modCount; + if (++size > threshold) + resize(); + ``` + **Node 节点类源码:** ```java