JDK1.8以前,HashMap采用位桶+链表实现,即使用链表处理冲突,同一hash值的链表都存储在一个链表里。但是当位于一个桶中的元素较多,即hash值相等的元素较多时,通过key值依次查找的效率较低。而JDK1.8中,HashMap采用位桶+链表+红黑树实现,当链表长度超过阈值(8)时(且数组长度大于64,如果小于64,给、会先扩容然后rehash),将链表转换为红黑树,这样大大减少了查找时间。

HashMap 存储结构

image.png

HashMap会将加入的键值对封装成一个Node节点,然后再加入到哈希表中。Node结构的源码如下
image.png

HashMap 各常量、成员变量作用

  1. /**
  2. * 创建 HashMap 时未指定初始容量情况下的默认容量(默认table大小)
  3. */
  4. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  5. /**
  6. * HashMap 的最大容量
  7. */
  8. static final int MAXIMUM_CAPACITY = 1 << 30;
  9. /**
  10. * HashMap 默认的装载因子,当 HashMap 中元素数量超过 容量*装载因子 时,进行 resize() 扩容操作
  11. */
  12. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  13. /**
  14. * 将链表转变为红黑树的阈值,树化阈值
  15. */
  16. static final int TREEIFY_THRESHOLD = 8;
  17. /**
  18. * 将红黑树转变为链表的阈值
  19. */
  20. static final int UNTREEIFY_THRESHOLD = 6;
  21. /**
  22. * 将链表转变为红黑树时,除了需要判断阈值,需要判断下此时数组容量。
  23. * 若是由于数组容量太小(小于 MIN_TREEIFY_CAPACITY )导致的 hash冲突太多,则不进行链表转变为红黑树操作,转为利用 resize() 函数对 hashMap 扩容
  24. */
  25. static final int MIN_TREEIFY_CAPACITY = 64;
  • 这里的容量大小指的是 哈希表中数组的大小(table大小)
  1. // 保存Node<K,V>节点的数组,位桶。 第一次put元素时初始化
  2. transient Node<K,V>[] table;
  3. // 由 hashMap 中 Node<K,V> 节点构成的 set
  4. transient Set<Map.Entry<K,V>> entrySet;
  5. // 记录 hashMap 当前存储的元素的数量
  6. transient int size;
  7. // 记录 hashMap 发生结构性变化的次数(注意 value 的覆盖不属于结构性变化)
  8. transient int modCount;
  9. // 扩容阈值,值应等于 table.length * loadFactor, size 超过这个值时进行 resize() 扩容
  10. int threshold;
  11. // 记录 hashMap 装载因子
  12. final float loadFactor;

构造方法

1、指定初始容量和装载因子
image.png

tableSizeFor(initialCapacity) 方法返回的值是最接近 initialCapacity 的2的幂,若指定初始容量为9,则实际 hashMap 容量为16。

此种方法创建的 hashMap 初始容量的值存在 threshold 中
image.png

2、指定初始容量,装载因子默认
image.png

3、所有参数均采用默认值
image.png

4、 根据传入的Map构造
image.png

put() 方法

image.png

这里的 hash(key) 方法其实就是给 key 的 hashcode值 加一个扰动,让 hashcode值 的高16位参与运算。
image.png

举个例子:
image.png

为什么要加这个扰动呢?

寻址算法 在计算 当前插入的node 在桶(table)中的位置的时候,是用的 hash()值 &(n-1)。
当 table 长度很小的时候,即桶的数量很小,假设当前为16,即16-1=15。如果不加这个扰动,则只有低位数的hashcode值能参与运算。
而让高16位参与运算可以更好的均匀散列,减少碰撞,进一步降低哈希冲突的几率。

再来看看 **putVal()** 方法

  1. final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
  2. Node<K,V>[] tab; Node<K,V> p; int n, i;
  3. // 初次插入元素时初始化哈希表
  4. if ((tab = table) == null || (n = tab.length) == 0)
  5. n = (tab = resize()).length;
  6. // 确定插入位置,若此位置没有元素则进行插入
  7. // 所用的计算方法为(n - 1) & hash,由于n 一定是2的幂次,这个操作相当于 hash % n
  8. if ((p = tab[i = (n - 1) & hash]) == null)
  9. tab[i] = newNode(hash, key, value, null);
  10. // 插入的位置已经有元素
  11. else {
  12. Node<K,V> e; K k;
  13. // 该位置的元素与待插入的元素相同(hash和key都相同),替换并返回旧值
  14. if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
  15. e = p;
  16. // 不相同,且该位置的元素已经树化
  17. else if (p instanceof TreeNode)
  18. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  19. // 不相同,且该位置的元素已经链化
  20. else {
  21. for (int binCount = 0; ; ++binCount) {
  22. // 尾插法
  23. if ((e = p.next) == null) {
  24. p.next = newNode(hash, key, value, null);
  25. // 如果链表长度大于8,将该链表树化
  26. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
  27. treeifyBin(tab, hash);
  28. break;
  29. }
  30. // 遍历过程中出现相同的元素,替换并返回旧值
  31. if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
  32. break;
  33. p = e;
  34. }
  35. }
  36. // 替换的过程
  37. if (e != null) { // existing mapping for key
  38. V oldValue = e.value;
  39. if (!onlyIfAbsent || oldValue == null)
  40. e.value = value;
  41. afterNodeAccess(e);
  42. return oldValue;
  43. }
  44. }
  45. // 记录修改的次数,替换旧值不算
  46. ++modCount;
  47. // 如果元素的个数 超过了扩容的阈值,进行扩容
  48. if (++size > threshold)
  49. resize();
  50. afterNodeInsertion(evict);
  51. return null;
  52. }

概括具体的过程
HashMap原理 - 图11

当某个桶的元素数量达到指定的阈值TREEIFY_THRESHOLD(8)时,HashMap会判断当前数组的 长度是否大于MIN_TREEIFY_CAPACITY(64),如果大于,那么这个桶的链表将会转为红黑树,否则HashMap将会扩容(在treeifyBin(tab, hash)方法里面判断的)。 当某个桶的红黑树节点的数量小于等于指定的阈值UNTREEIFY_THRESHOLD(6)时,那么在扩容的时候,这个桶的红黑树将转为链表。

resize() 方法 扩容

为什么需要扩容?

解决哈希冲突导致的链化严重,影响查询效率的问题。

什么情况下进行扩容?

  1. 当元素个数(size)大于扩容阈值(threshold)时,threshold = table.length * loadFactor
  2. 初次向hashmap中添加元素时

扩容使用的是 **resize()** 方法

  1. final Node<K,V>[] resize() {
  2. Node<K,V>[] oldTab = table;
  3. int oldCap = (oldTab == null) ? 0 : oldTab.length;
  4. int oldThr = threshold;
  5. int newCap, newThr = 0;
  6. // 确定 扩容之后的大小 和 扩容阈值
  7. if (oldCap > 0) {
  8. if (oldCap >= MAXIMUM_CAPACITY) {
  9. threshold = Integer.MAX_VALUE;
  10. return oldTab;
  11. }
  12. else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
  13. oldCap >= DEFAULT_INITIAL_CAPACITY)
  14. newThr = oldThr << 1; // double threshold
  15. }
  16. else if (oldThr > 0) // initial capacity was placed in threshold
  17. newCap = oldThr;
  18. else { // zero initial threshold signifies using defaults
  19. newCap = DEFAULT_INITIAL_CAPACITY;
  20. newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
  21. }
  22. if (newThr == 0) {
  23. float ft = (float)newCap * loadFactor;
  24. newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
  25. (int)ft : Integer.MAX_VALUE);
  26. }
  27. threshold = newThr;
  28. // 创建新的哈希表
  29. @SuppressWarnings({"rawtypes","unchecked"})
  30. Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
  31. table = newTab;
  32. // 遍历旧的哈希表
  33. if (oldTab != null) {
  34. for (int j = 0; j < oldCap; ++j) {
  35. Node<K,V> e;
  36. if ((e = oldTab[j]) != null) {
  37. oldTab[j] = null;
  38. // 只有一个元素的情况下,计算在新哈希表中的位置,直接赋值
  39. if (e.next == null)
  40. newTab[e.hash & (newCap - 1)] = e;
  41. // 已经树化,要进行 红黑树的 rehash 操作
  42. // 跟链表一样,也是用同样的方法将节点分不到两个链表上,注意还得计算新链表的长度,判断是否需要树化
  43. else if (e instanceof TreeNode)
  44. ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
  45. // 链化,将链表中的元素分成两个链表,分别赋值给新的哈希表
  46. else { // preserve order
  47. Node<K,V> loHead = null, loTail = null;
  48. Node<K,V> hiHead = null, hiTail = null;
  49. Node<K,V> next;
  50. do {
  51. next = e.next;
  52. // 根据算法 e.hash & oldCap 判断节点位置 rehash 后是否发生改变
  53. if ((e.hash & oldCap) == 0) {
  54. if (loTail == null)
  55. loHead = e;
  56. else
  57. loTail.next = e;
  58. loTail = e;
  59. }
  60. else {
  61. if (hiTail == null)
  62. hiHead = e;
  63. else
  64. hiTail.next = e;
  65. hiTail = e;
  66. }
  67. } while ((e = next) != null);
  68. if (loTail != null) {
  69. loTail.next = null;
  70. newTab[j] = loHead;
  71. }
  72. if (hiTail != null) {
  73. hiTail.next = null;
  74. newTab[j + oldCap] = hiHead;
  75. }
  76. }
  77. }
  78. }
  79. }
  80. return newTab;
  81. }

resize()方法中比较重要的是 链表和红黑树的 rehash 操作,先来说下 rehash 的实现原理:

我们在扩容的时候,一般是把长度扩为原来2倍,又因为寻址算法的计算方式为e.hash & (newCap - 1),所以元素的位置要么是在原位置,要么是在原位置再移动2次幂的位置。

看下图可以明白这句话的意思。n为table的长度,图(a)表示扩容前的key1和key2两种key确定索引位置的示例,图(b)表示扩容后key1和key2两种key确定索引位置的示例。
image.png
可以看出 key1扩容前和扩容后计算出的在table中的地址变,key2在原来的基础上加了OldCap。

因此,我们在扩充HashMap的时候,只需要看看原来的hash值新增的那个bit是1还是0就好了,是0的话索引没变,是1的话索引变成“原索引+oldCap”,可以根据算法 **e.hash & oldCap** 判断节点位置 rehash 后是否发生改变。可以看看下图为16扩充为32的resize示意图:
image.png
这个算法很巧妙,既省去了重新计算在newTable中的位置,而且同时,由于新增的1bit是0还是1可以认为是随机的,因此resize的过程,均匀的把之前的冲突的节点分散到新的槽中了。

get() 方法

final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

get() 方法调用的是 getNode() 方法,通过 hash(key)和key 一起进行查找。
先通过hash(key)找到在 table 中的位置,在对key进行比较,若相同,就返回。