HashMap 中的容量与扩容实现,细致入微,值的一品!
- 时间:
- 浏览:0
前言
开心一刻
巴闭,你的脚为什么么会有味道,我要闻闻看是都有好吃的火锅的面的,嗯~~爸比你的脚臭死啦!! ……
高手过招,招招致命
JDK1.8 中 HashMap 的底层实现,我相信亲们都能说上来个 一二,底层数据行态 数组 + 链表(或红黑树) ,源码如下
/** * 数组 */ 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; } 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; } } /** * 红黑树行态 */ static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { TreeNode<K,V> parent; // red-black tree links TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev; // needed to unlink next upon deletion boolean red; ...
但面试往往会问的比较细,类事下面的容量现象,亲们能答上来几只?
1、table 的初始化时机是许多从前,初始化的 table.length 是几只、阀值(threshold)是几只,实际能容下几只元素
2、许多从前触发扩容,扩容从前的 table.length、阀值各是几只?
3、table 的 length 为许多是 2 的 n 次幂
4、求索引的从前为许多是:h&(length-1),而都有 h&length,更都有 h%length
5、 Map map = new HashMap(4000); 当亲们存入几只个元素完会触发map的扩容; Map map1 = new HashMap(40000); 亲们存入第 4000有一一十个 多元素完会触发 map1 扩容吗
6、为许多加载因子的默认值是 0.75,可是我我不推荐亲们修改
可能性亲们平时关注的少,一旦碰上从前的 连击 + 暴击,亲们往往不知所措、无从应对;接下来亲们看看中间的 6 个现象,是都有真的难到无法理解 ,还是亲们存在问题细心、在自信的自我认为
斗智斗勇,见招拆招
上述的现象,亲们咋样去找答案 ? 土办法有全都种,用的最多的,我要应该是上网查资料、看别人的博客,但我认为最有效、准确的土办法是读源码
现象 1:table 的初始化
HashMap 的构造土办法有如下 4 种
构造土办法 4 和 构造土办法 1 实际应用的很多,构造土办法 2 直接调用的 1(底层实现完整一致),构造土办法 2 和 构造土办法 3 比较常用,而最常用的是构造土办法 3;此时亲们以构造土办法 3 为前提来分析,而构造土办法 2 亲们则在现象 5 中来分析
使用土办法 1 实例化 HashMap 的从前,table 并未进行初始化,那 table 是啥刚刚进行初始化的了 ? 平时亲们是咋样使用 HashMap 的,先实例化、可是我我 put、可是我我进行许多操作,如下
Map<String,Object> map = new HashMap();
map.put("name", "张三");
map.put("age", 21);
// 后续操作
...
既然实例化的从前未进行 table 的初始化,那是都有在 put 的从前初始化的了,亲们来确认下
resize() 初始化 table 或 对 table 进行双倍扩容,源码如下(注意看注释)
/** * Initializes or doubles table size. If null, allocates in * accord with initial capacity target held in field threshold. * Otherwise, because we are using power-of-two expansion, the * elements from each bin must either stay at same index, or move * with a power of two offset in the new table. * * @return the table */ final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; // 第一次 put 的从前,table = null int oldCap = (oldTab == null) ? 0 : oldTab.length; // oldCap = 0 int oldThr = threshold; // threshold=0, oldThr = 0 int newCap, newThr = 0; if (oldCap > 0) { // 条件不满足,往下走 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { // zero initial threshold signifies using defaults 走到这里,进行默认初始化 newCap = DEFAULT_INITIAL_CAPACITY; // DEFAULT_INITIAL_CAPACITY = 1 << 4 = 16, newCap = 16; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // newThr = 0.75 * 16 = 12; } if (newThr == 0) { // 条件不满足 float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; // threshold = 12; 重置阀值为12 @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; // 初始化 newTab, length = 16; table = newTab; // table 初始化完成, length = 16; if (oldTab != null) { // 此时条件不满足,后续扩容的从前,走此if分支 将数组元素qq克隆好友 到新数组 for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null; if (e.next == null) newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order 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; // 新数组 }
自此,现象 1 的答案就明了了
table 的初始化时机是许多从前
一般清况
下,在第一次 put 的从前,调用 resize 土办法进行 table 的初始化(懒初始化,懒加载思想在全都框架中都有应用!)
初始化的 table.length 是几只、阀值(threshold)是几只,实际能容下几只元素
默认清况
下,table.length = 16; 指定了 initialCapacity 的清况
倒进现象 5 中分析
默认清况
下,threshold = 12; 指定了 initialCapacity 的清况
倒进现象 5 中分析
默认清况
下,能存放 12 个元素,当存放第 13 个元素后进行扩容
现象 2 :table 的扩容
putVal 源码如下
/** * 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; 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); 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; } } ++modCount; if (++size > threshold) // 当size(已存放元素个数) > thrshold(阀值),进行扩容 resize(); afterNodeInsertion(evict); return null; }
还是调用 resize() 进行扩容,但与初始化时不同(注意看注释)
/** * Initializes or doubles table size. If null, allocates in * accord with initial capacity target held in field threshold. * Otherwise, because we are using power-of-two expansion, the * elements from each bin must either stay at same index, or move * with a power of two offset in the new table. * * @return the table */ final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; // 此时的 table != null,oldTab 指向旧的 table int oldCap = (oldTab == null) ? 0 : oldTab.length; // oldCap = table.length; 第一次扩容时是 16 int oldThr = threshold; // threshold=12, oldThr = 12; int newCap, newThr = 0; if (oldCap > 0) { // 条件满足,走此分支 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && // oldCap左移一位; newCap = 16 << 1 = 32; oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold // newThr = 12 << 1 = 24; } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY; // DEFAULT_INITIAL_CAPACITY = 1 << 4 = 16, newCap = 16; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } if (newThr == 0) { // 条件不满足 float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; // threshold = newThr = 24; 重置阀值为 24 @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; // 初始化 newTab, length = 32; table = newTab; // table 指向 newTab, length = 32; if (oldTab != null) { // 扩容后,将 oldTab(旧table) 中的元素移到 newTab(新table)中 for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null; if (e.next == null) newTab[e.hash & (newCap - 1)] = e; // else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order 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; }
自此,现象 2 的答案也就清晰了
许多从前触发扩容,扩容从前的 table.length、阀值各是几只
当 size > threshold 的从前进行扩容
扩容从前的 table.length = 旧 table.length * 2,
扩容从前的 threshold = 旧 threshold * 2
现象 3、4 :2 的 n 次幂
table 是有一一十个 多数组,这样咋样最快的将元素 e 倒进数组 ? 当然是找到元素 e 在 table 中对应的位置 index ,可是我我 table[index] = e; 就好了;咋样找到 e 在 table 中的位置了 ? 亲们知道不到通过数组下标(索引)操作数组,而数组的下标类型又是 int ,可能性 e 是 int 类型,那好说,就直接用 e 来做数组下标(若 e > table.length,则须要 e % table.length 来获取下标),可 key - value 中的 key 类型不一定,全都亲们须要一种生活统一的土办法将 key 转换成 int ,最好是有一一十个 多 key 对应有一一十个 多唯一的 int (目前还可能性性, int有范围限制,对转换土办法要求也极高),全都引入了 hash 土办法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); // 这里的外理,有兴趣的须要琢磨下;都都可不还可以减少碰撞
}
实现 key 到 int 的转换(关于 hash,本文不展开讨论)。拿到了 key 对应的 int h 从前,亲们最容易想到的对 value 的 put 和 get 操作跟我说如下
// put
table[h % table.length] = value;
// get
e = table[h % table.length];
直接取模是亲们最容易想到的获取下标的土办法,可是我我最高效的土办法吗 ?
亲们知道计算机中的四则运算最终完会转换成二进制的位运算
亲们须要发现,不到 & 数是1时,& 运算的结果与被 & 数一致
1&1=1;
0&1=0;
1&0=0;
0&0=0;
这同样适用于多位操作数
1010&1111=1010; => 10&15=10;
1011&1111=1011; => 11&15=11;
01010&40000=00000; => 10&16=0;
01011&40000=00000; => 11&16=0;
亲们是都有又有所发现: 10 & 16 与 11 & 16 得到的结果一样,也假如有一天冲突(碰撞)了,这样 10 和 11 对应的 value 会在同有一一十个 多链表中,而 table 的许多位置则永远完会有元素,这就原因 table 的空间未得到充分利用,并肩还降低了 put 和 get 的传输传输速率(对比数组和链表);可能性是 2 个数进行 & 运算,全都结果由这有一一十个 多数决定,可能性亲们把这有一一十个 多数都做下限制,那得到的结果是都有可控制在亲们你要 的范围内了 ? 亲们须要利用好 & 运算的特点,当右边的数的低位二进制是连续的 1 ,且左边是有一一十个 多均匀的数(须要 hash 土办法实现,尽量保证 key 的 h 唯一),这样得到的结果就比较完美了。低位二进制连续的 1,亲们很容易想到 2^n - 1; 而关于左边均匀的数,则通过 hash 土办法来实现,这里不做细究了。
自此,2 的 n 次幂的相关现象就清楚了
table 的 length 为许多是 2 的 n 次幂
为了利用位运算 & 求 key 的下标
求索引的从前为许多是:h&(length-1),而都有 h&length,更都有 h%length
h%length 传输传输速率不如位运算快
h&length 会提高碰撞几率,原因 table 的空间得不到更充分的利用、降低 table 的操作传输传输速率
给各位留个现象:为许多不直接用 2^n-1 作为 table.length ? 欢迎评论区留言
现象 5:指定 initialCapacity
当亲们指定了 initialCapacity,HashMap的构造土办法许多许不同,如下所示
调用 tableSizeFor 进行 threshold 的初始化
真是此处初始化的是 threshold,但中间初始化 table 的从前,会将其用于 table 的 length,同完会重置 threshold 为 table.length * loadFactor
自此,现象 5 也就清楚了
Map map = new HashMap(4000); 当亲们存入几只个元素完会触发map的扩容
此时的 table.length = 2^10 = 1024; threshold = 1024 * 0.75 = 768; 全都存入第 769 个元素时进行扩容
Map map1 = new HashMap(40000); 亲们存入第 4000有一一十个
多元素完会触发 map1 扩容吗
此时的 table.length = 2^14 = 16384; threshold = 16384 * 0.75 = 12288; 全都存入第 40001 个元素时完会进行扩容
现象6:加载因子
为许多加载因子的默认值是 0.75,可是我我不推荐亲们修改
可能性loadFactor太小,这样map中的table须要不断的扩容,扩容是个耗时的过程
可能性loadFactor很多,这样map中table装进了假如有一天完会扩容,原因冲突很多,外理冲突而起的链表这样长,传输传输速率这样低
而 0.75 这是有一一十个
多折中的值,是有一一十个
多比较理想的值
总结
1、table.length = 2^n,是为了能利用位运算(&)来求 key 的下标,而 h&(length-1) 是为了充分利用 table 的空间,并减少 key 的碰撞
2、加载因子太小, table 须要不断的扩容,影响 put 传输传输速率;很多会原因碰撞很多,链表这样长(转红黑树),影响传输传输速率;0.75 是有一一十个 多比较理想的中间值
3、table.length = 2^n、hash 土办法获取 key 的 h、加载因子 0.75、数组 + 链表(或红黑树),一环扣一环,保证了 key 在 table 中的均匀分配,充分利用了空间,也保证了操作传输传输速率
环环相扣的,而都有心血来潮的随意外理;缺了一环,许多的环就无意义了!
4、网上有个 put 土办法的流程图画的挺好,我就偷懒了
参考
java提高篇(二三)-----HashMap
【原创】HashMap复习精讲
面试官:"准备用HashMap存1w条数据,构造时传40000完会触发扩容吗?"