JDK1.8 中 HashMap 的底层实现,我相信大家都能说上来个 一二,底层数据结构 数组 + 链表(或红黑树) ,源码如下

  1. /**
  2. * 数组
  3. */
  4. transient Node<K,V>[] table;
  5. /**
  6. * 链表结构
  7. */
  8. static class Node<K,V> implements Map.Entry<K,V> {
  9. final int hash;
  10. final K key;
  11. V value;
  12. Node<K,V> next;
  13. Node(int hash, K key, V value, Node<K,V> next) {
  14. this.hash = hash;
  15. this.key = key;
  16. this.value = value;
  17. this.next = next;
  18. }
  19. public final K getKey() { return key; }
  20. public final V getValue() { return value; }
  21. public final String toString() { return key + "=" + value; }
  22. public final int hashCode() {
  23. return Objects.hashCode(key) ^ Objects.hashCode(value);
  24. }
  25. public final V setValue(V newValue) {
  26. V oldValue = value;
  27. value = newValue;
  28. return oldValue;
  29. }
  30. public final boolean equals(Object o) {
  31. if (o == this)
  32. return true;
  33. if (o instanceof Map.Entry) {
  34. Map.Entry<?,?> e = (Map.Entry<?,?>)o;
  35. if (Objects.equals(key, e.getKey()) &&
  36. Objects.equals(value, e.getValue()))
  37. return true;
  38. }
  39. return false;
  40. }
  41. }
  42. /**
  43. * 红黑树结构
  44. */
  45. static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
  46. TreeNode<K,V> parent; // red-black tree links
  47. TreeNode<K,V> left;
  48. TreeNode<K,V> right;
  49. TreeNode<K,V> prev; // needed to unlink next upon deletion
  50. boolean red;
  51. ...

美团HashMap 面试 - 图1
但面试往往会问的比较细,例如下面的容量问题,我们能答上来几个?
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(1000); 当我们存入多少个元素时会触发map的扩容;Map map1 = new HashMap(10000); 我们存入第 10001个元素时会触发 map1 扩容吗
6、为什么加载因子的默认值是 0.75,并且不推荐我们修改
由于我们平时关注的少,一旦碰上这样的 连击 + 暴击,我们往往不知所措、无从应对;接下来我们看看上面的 6 个问题,是不是真的难到无法理解 ,还是我们不够细心、在自信的自我认为
上述的问题,我们如何去找答案 ? 方式有很多种,用的最多的,我想应该是上网查资料、看别人的博客,但我认为最有效、准确的方式是读源码

问题 1:table 的初始化

HashMap 的构造方法有如下 4 种

  1. /**
  2. * 构造方法 1
  3. *
  4. * 通过 指定的 initialCapacity 和 loadFactor 实例化一个空的 HashMap 对象
  5. */
  6. public HashMap(int initialCapacity, float loadFactor) {
  7. if (initialCapacity < 0)
  8. throw new IllegalArgumentException("Illegal initial capacity: " +
  9. initialCapacity);
  10. if (initialCapacity > MAXIMUM_CAPACITY)
  11. initialCapacity = MAXIMUM_CAPACITY;
  12. if (loadFactor <= 0 || Float.isNaN(loadFactor))
  13. throw new IllegalArgumentException("Illegal load factor: " +
  14. loadFactor);
  15. this.loadFactor = loadFactor;
  16. this.threshold = tableSizeFor(initialCapacity);
  17. }
  18. /**
  19. * 构造方法 2
  20. *
  21. * 通过指定的 initialCapacity 和 默认的 loadFactor(0.75) 实例化一个空的 HashMap 对象
  22. */
  23. public HashMap(int initialCapacity) {
  24. this(initialCapacity, DEFAULT_LOAD_FACTOR);
  25. }
  26. /**
  27. * 构造方法 3
  28. *
  29. * 通过默认的 initialCapacity 和 默认的 loadFactor(0.75) 实例化一个空的 HashMap 对象
  30. */
  31. public HashMap() {
  32. this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
  33. }
  34. /**
  35. *
  36. * 构造方法 4
  37. * 通过指定的 Map 对象实例化一个 HashMap 对象
  38. */
  39. public HashMap(Map<? extends K, ? extends V> m) {
  40. this.loadFactor = DEFAULT_LOAD_FACTOR;
  41. putMapEntries(m, false);
  42. }

构造方式 4 和 构造方式 1 实际应用的不多,构造方式 2 直接调用的 1(底层实现完全一致),构造方式 2 和 构造方式 3 比较常用,而最常用的是构造方式 3;此时我们以构造方式 3 为前提来分析,而构造方式 2 我们则在问题 5 中来分析
使用方式 1 实例化 HashMap 的时候,table 并未进行初始化,那 table 是何时进行初始化的了 ?平时我们是如何使用 HashMap 的,先实例化、然后 put、然后进行其他操作,如下

  1. Map<String,Object> map = new HashMap();
  2. map.put("name", "张三");
  3. map.put("age", 21);
  4. // 后续操作
  5. ...

既然实例化的时候未进行 table 的初始化,那是不是在 put 的时候初始化的了,我们来确认下
美团HashMap 面试 - 图2
resize() 初始化 table 或 对 table 进行双倍扩容,源码如下(注意看注释)

  1. /**
  2. * Initializes or doubles table size. If null, allocates in
  3. * accord with initial capacity target held in field threshold.
  4. * Otherwise, because we are using power-of-two expansion, the
  5. * elements from each bin must either stay at same index, or move
  6. * with a power of two offset in the new table.
  7. *
  8. * @return the table
  9. */
  10. final Node<K,V>[] resize() {
  11. Node<K,V>[] oldTab = table; // 第一次 put 的时候,table = null
  12. int oldCap = (oldTab == null) ? 0 : oldTab.length; // oldCap = 0
  13. int oldThr = threshold; // threshold=0, oldThr = 0
  14. int newCap, newThr = 0;
  15. if (oldCap > 0) { // 条件不满足,往下走
  16. if (oldCap >= MAXIMUM_CAPACITY) {
  17. threshold = Integer.MAX_VALUE;
  18. return oldTab;
  19. }
  20. else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
  21. oldCap >= DEFAULT_INITIAL_CAPACITY)
  22. newThr = oldThr << 1; // double threshold
  23. }
  24. else if (oldThr > 0) // initial capacity was placed in threshold
  25. newCap = oldThr;
  26. else { // zero initial threshold signifies using defaults 走到这里,进行默认初始化
  27. newCap = DEFAULT_INITIAL_CAPACITY; // DEFAULT_INITIAL_CAPACITY = 1 << 4 = 16, newCap = 16;
  28. newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // newThr = 0.75 * 16 = 12;
  29. }
  30. if (newThr == 0) { // 条件不满足
  31. float ft = (float)newCap * loadFactor;
  32. newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
  33. (int)ft : Integer.MAX_VALUE);
  34. }
  35. threshold = newThr; // threshold = 12; 重置阀值为12
  36. @SuppressWarnings({"rawtypes","unchecked"})
  37. Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; // 初始化 newTab, length = 16;
  38. table = newTab; // table 初始化完成, length = 16;
  39. if (oldTab != null) { // 此时条件不满足,后续扩容的时候,走此if分支 将数组元素复制到新数组
  40. for (int j = 0; j < oldCap; ++j) {
  41. Node<K,V> e;
  42. if ((e = oldTab[j]) != null) {
  43. oldTab[j] = null;
  44. if (e.next == null)
  45. newTab[e.hash & (newCap - 1)] = e;
  46. else if (e instanceof TreeNode)
  47. ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
  48. else { // preserve order
  49. Node<K,V> loHead = null, loTail = null;
  50. Node<K,V> hiHead = null, hiTail = null;
  51. Node<K,V> next;
  52. do {
  53. next = e.next;
  54. if ((e.hash & oldCap) == 0) {
  55. if (loTail == null)
  56. loHead = e;
  57. else
  58. loTail.next = e;
  59. loTail = e;
  60. }
  61. else {
  62. if (hiTail == null)
  63. hiHead = e;
  64. else
  65. hiTail.next = e;
  66. hiTail = e;
  67. }
  68. } while ((e = next) != null);
  69. if (loTail != null) {
  70. loTail.next = null;
  71. newTab[j] = loHead;
  72. }
  73. if (hiTail != null) {
  74. hiTail.next = null;
  75. newTab[j + oldCap] = hiHead;
  76. }
  77. }
  78. }
  79. }
  80. }
  81. return newTab; // 新数组
  82. }

自此,问题 1 的答案就明了了
table 的初始化时机是什么时候
一般情况下,在第一次 put 的时候,调用 resize 方法进行 table 的初始化(懒初始化,懒加载思想在很多框架中都有应用!)
初始化的 table.length 是多少、阀值(threshold)是多少,实际能容下多少元素

  • 默认情况下,table.length = 16; 指定了 initialCapacity 的情况放到问题 5 中分析
  • 默认情况下,threshold = 12; 指定了 initialCapacity 的情况放到问题 5 中分析
  • 默认情况下,能存放 12 个元素,当存放第 13 个元素后进行扩容

    问题 2 :table 的扩容

    putVal 源码如下

    1. /**
    2. * Implements Map.put and related methods
    3. *
    4. * @param hash hash for key
    5. * @param key the key
    6. * @param value the value to put
    7. * @param onlyIfAbsent if true, don't change existing value
    8. * @param evict if false, the table is in creation mode.
    9. * @return previous value, or null if none
    10. */
    11. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
    12. boolean evict) {
    13. Node<K,V>[] tab; Node<K,V> p; int n, i;
    14. if ((tab = table) == null || (n = tab.length) == 0)
    15. n = (tab = resize()).length;
    16. if ((p = tab[i = (n - 1) & hash]) == null)
    17. tab[i] = newNode(hash, key, value, null);
    18. else {
    19. Node<K,V> e; K k;
    20. if (p.hash == hash &&
    21. ((k = p.key) == key || (key != null && key.equals(k))))
    22. e = p;
    23. else if (p instanceof TreeNode)
    24. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
    25. else {
    26. for (int binCount = 0; ; ++binCount) {
    27. if ((e = p.next) == null) {
    28. p.next = newNode(hash, key, value, null);
    29. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
    30. treeifyBin(tab, hash);
    31. break;
    32. }
    33. if (e.hash == hash &&
    34. ((k = e.key) == key || (key != null && key.equals(k))))
    35. break;
    36. p = e;
    37. }
    38. }
    39. if (e != null) { // existing mapping for key
    40. V oldValue = e.value;
    41. if (!onlyIfAbsent || oldValue == null)
    42. e.value = value;
    43. afterNodeAccess(e);
    44. return oldValue;
    45. }
    46. }
    47. ++modCount;
    48. if (++size > threshold) // 当size(已存放元素个数) > thrshold(阀值),进行扩容
    49. resize();
    50. afterNodeInsertion(evict);
    51. return null;
    52. }

    还是调用 resize() 进行扩容,但与初始化时不同(注意看注释)

    1. /**
    2. * Initializes or doubles table size. If null, allocates in
    3. * accord with initial capacity target held in field threshold.
    4. * Otherwise, because we are using power-of-two expansion, the
    5. * elements from each bin must either stay at same index, or move
    6. * with a power of two offset in the new table.
    7. *
    8. * @return the table
    9. */
    10. final Node<K,V>[] resize() {
    11. Node<K,V>[] oldTab = table; // 此时的 table != null,oldTab 指向旧的 table
    12. int oldCap = (oldTab == null) ? 0 : oldTab.length; // oldCap = table.length; 第一次扩容时是 16
    13. int oldThr = threshold; // threshold=12, oldThr = 12;
    14. int newCap, newThr = 0;
    15. if (oldCap > 0) { // 条件满足,走此分支
    16. if (oldCap >= MAXIMUM_CAPACITY) {
    17. threshold = Integer.MAX_VALUE;
    18. return oldTab;
    19. }
    20. else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && // oldCap左移一位; newCap = 16 << 1 = 32;
    21. oldCap >= DEFAULT_INITIAL_CAPACITY)
    22. newThr = oldThr << 1; // double threshold // newThr = 12 << 1 = 24;
    23. }
    24. else if (oldThr > 0) // initial capacity was placed in threshold
    25. newCap = oldThr;
    26. else { // zero initial threshold signifies using defaults
    27. newCap = DEFAULT_INITIAL_CAPACITY; // DEFAULT_INITIAL_CAPACITY = 1 << 4 = 16, newCap = 16;
    28. newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    29. }
    30. if (newThr == 0) { // 条件不满足
    31. float ft = (float)newCap * loadFactor;
    32. newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
    33. (int)ft : Integer.MAX_VALUE);
    34. }
    35. threshold = newThr; // threshold = newThr = 24; 重置阀值为 24
    36. @SuppressWarnings({"rawtypes","unchecked"})
    37. Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; // 初始化 newTab, length = 32;
    38. table = newTab; // table 指向 newTab, length = 32;
    39. if (oldTab != null) { // 扩容后,将 oldTab(旧table) 中的元素移到 newTab(新table)中
    40. for (int j = 0; j < oldCap; ++j) {
    41. Node<K,V> e;
    42. if ((e = oldTab[j]) != null) {
    43. oldTab[j] = null;
    44. if (e.next == null)
    45. newTab[e.hash & (newCap - 1)] = e; //
    46. else if (e instanceof TreeNode)
    47. ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
    48. else { // preserve order
    49. Node<K,V> loHead = null, loTail = null;
    50. Node<K,V> hiHead = null, hiTail = null;
    51. Node<K,V> next;
    52. do {
    53. next = e.next;
    54. if ((e.hash & oldCap) == 0) {
    55. if (loTail == null)
    56. loHead = e;
    57. else
    58. loTail.next = e;
    59. loTail = e;
    60. }
    61. else {
    62. if (hiTail == null)
    63. hiHead = e;
    64. else
    65. hiTail.next = e;
    66. hiTail = e;
    67. }
    68. } while ((e = next) != null);
    69. if (loTail != null) {
    70. loTail.next = null;
    71. newTab[j] = loHead;
    72. }
    73. if (hiTail != null) {
    74. hiTail.next = null;
    75. newTab[j + oldCap] = hiHead;
    76. }
    77. }
    78. }
    79. }
    80. }
    81. return newTab;
    82. }

    自此,问题 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 方法
    1. static final int hash(Object key) {
    2. int h;
    3. return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); // 这里的处理,有兴趣的可以琢磨下;能够减少碰撞
    4. }
    实现 key 到 int 的转换(关于 hash,本文不展开讨论)。拿到了 key 对应的 int h 之后,我们最容易想到的对 value 的 put 和 get 操作也许如下 ```java // put
    table[h % table.length] = value;

// get
e = table[h % table.length];

  1. 直接取模是我们最容易想到的获取下标的方法,但是最高效的方法吗 ?<br />我们知道计算机中的四则运算最终都会转换成二进制的位运算<br />![](https://cdn.nlark.com/yuque/0/2021/webp/1311515/1638712287393-68c8091b-da02-4e3f-ace1-17a51f742e4c.webp#align=left&display=inline&height=91&margin=%5Bobject%20Object%5D&originHeight=91&originWidth=241&size=0&status=done&style=none&width=241)<br />我们可以发现,只有 & 数是1时,& 运算的结果与被 & 数一致

1&1=1;
0&1=0;
1&0=0;
0&0=0;

  1. 这同样适用于多位操作数

1010&1111=1010; => 10&15=10;
1011&1111=1011; => 11&15=11;
01010&10000=00000; => 10&16=0;
01011&10000=00000; => 11&16=0;

  1. 我们是不是又有所发现:10 & 16 11 & 16 得到的结果一样,也就是冲突(碰撞)了,那么 10 11 对应的 value 会在同一个链表中,而 table 的有些位置则永远不会有元素,这就导致 table 的空间未得到充分利用,同时还降低了 put get 的效率(对比数组和链表);由于是 2 个数进行 & 运算,所以结果由这两个数决定,如果我们把这两个数都做下限制,那得到的结果是不是可控制在我们想要的范围内了 ?<br />我们需要利用好 & 运算的特点,当右边的数的低位二进制是连续的 1 ,且左边是一个均匀的数(需要 hash 方法实现,尽量保证 key h 唯一),那么得到的结果就比较完美了。低位二进制连续的 1,我们很容易想到 2^n - 1; 而关于左边均匀的数,则通过 hash 方法来实现,这里不做细究了。<br />自此,2 n 次幂的相关问题就清楚了<br />**table length 为什么是 2 n 次幂**<br />为了利用位运算 & key 的下标<br />**求索引的时候为什么是:h&(length-1),而不是 h&length,更不是 h%length**
  2. - h%length 效率不如位运算快<br />
  3. - h&length 会提高碰撞几率,导致 table 的空间得不到更充分的利用、降低 table 的操作效率<br />
  4. 给各位留个疑问:为什么不直接用 2^n-1 作为 table.length ?欢迎评论区留言
  5. <a name="lO8xb"></a>
  6. ### 问题 5:指定 initialCapacity
  7. 当我们指定了 initialCapacityHashMap的构造方法有些许不同,如下所示<br />![](https://cdn.nlark.com/yuque/0/2021/gif/1311515/1638712287563-47d9bf03-4224-42d8-b6f9-930c3d7938e8.gif#align=left&display=inline&height=426&margin=%5Bobject%20Object%5D&originHeight=426&originWidth=640&size=0&status=done&style=none&width=640)<br />调用 tableSizeFor 进行 threshold 的初始化
  8. ```java
  9. /**
  10. * Returns a power of two size for the given target capacity.
  11. * 返回 >= cap 最小的 2^n
  12. * cap = 10, 则返回 2^4 = 16;
  13. * cap = 5, 则返回 2^3 = 8;
  14. */
  15. static final int tableSizeFor(int cap) {
  16. int n = cap - 1;
  17. n |= n >>> 1;
  18. n |= n >>> 2;
  19. n |= n >>> 4;
  20. n |= n >>> 8;
  21. n |= n >>> 16;
  22. return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
  23. }

虽然此处初始化的是 threshold,但后面初始化 table 的时候,会将其用于 table 的 length,同时会重置 threshold 为 table.length loadFactor
自此,问题 5 也就清楚了
Map map = new HashMap(1000); 当我们存入多少个元素时会触发map的扩容
此时的 table.length = 2^10 = 1024; threshold = 1024
0.75 = 768; 所以存入第 769 个元素时进行扩容
Map map1 = new HashMap(10000); 我们存入第 10001个元素时会触发 map1 扩容吗
此时的 table.length = 2^14 = 16384; threshold = 16384 * 0.75 = 12288; 所以存入第 10001 个元素时不会进行扩容

问题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 方法的流程图画的挺好,我就偷懒了
    美团HashMap 面试 - 图3