当前位置:   article > 正文

HashMap的底层实现_hashmap 的底层实现方式

hashmap 的底层实现方式

1、1.7版本的底层实现

HashMap在1.7版本中数据结构是数组+链表,

1.1 put方法

put方法中操作步骤:

(1)、对key计算相应的hash值,然后通过hash & table.length-1计算可以获得到在hash表中中相应的桶位置,循环遍历其链表,比较其key值,如果相等,则更新其value的值

(2)如果不相等,则判断是否需要扩容,其中扩容的判断条件是,其size>table.length*0.75.其中0.75是负载因子,如果超过,则扩容。没有超过,则头插入的方式,插入到链表表头。

  1. public V put(K key, V value) {
  2. // 如果key为null,单独处理
  3. if (key == null)
  4. return putForNullKey(value);
  5. int hash = hash(key);//计算出哈希值
  6. int i = indexFor(hash, table.length);//通过哈希值计算出哈希桶的位置
  7. //遍历链表,判断是否有key相等(即哈希值相等)的节点,如果有,则更新值,并返回旧的值
  8. for (Entry<K,V> e = table[i]; e != null; e = e.next) {
  9. Object k;
  10. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
  11. V oldValue = e.value;
  12. e.value = value;
  13. e.recordAccess(this);
  14. return oldValue;
  15. }
  16. }
  17. modCount++; // 更新次数+1
  18. addEntry(hash, key, value, i); // 没有找到相同的
  19. return null;
  20. }
  21. void addEntry(int hash, K key, V value, int bucketIndex) {
  22. if ((size >= threshold) && (null != table[bucketIndex])) {
  23. resize(2 * table.length);//自动扩容,并重新哈希
  24. hash = (null != key) ? hash(key) : 0;
  25. bucketIndex = hash & (table.length-1);//hash%table.length
  26. }
  27. //在冲突链表头部插入新的entry
  28. Entry<K,V> e = table[bucketIndex];
  29. table[bucketIndex] = new Entry<>(hash, key, value, e);
  30. size++;
  31. }
  32. void resize(int newCapacity) {
  33. //这里获取老table的长度,如果老table的长度已经是最大的容量了,那就没必要扩容了,直接返回。
  34. Entry[] oldTable = table;
  35. int oldCapacity = oldTable.length;
  36. if (oldCapacity == MAXIMUM_CAPACITY) {
  37. threshold = Integer.MAX_VALUE;
  38. return;
  39. }
  40. //如果可以扩容,则new一个新的数组
  41. Entry[] newTable = new Entry[newCapacity];
  42. //transfer方法将老数组的数据copy到新数组当中
  43. transfer(newTable, initHashSeedAsNeeded(newCapacity));
  44. //transfer完了, 就把新数组赋给全局变量table
  45. table = newTable;
  46. //再用新数组的容量计算新的阈值
  47. threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
  48. }
  49. void transfer(Entry[] newTable, boolean rehash) {
  50. int newCapacity = newTable.length;
  51. for (Entry<K,V> e : table) {
  52. while(null != e) {
  53. Entry<K,V> next = e.next;
  54. if (rehash) {
  55. e.hash = null == e.key ? 0 : hash(e.key); //重新计算hash值
  56. }
  57. int i = indexFor(e.hash, newCapacity);
  58. e.next = newTable[i];
  59. newTable[i] = e;
  60. e = next;//继续下一个元素
  61. }
  62. }
  63. }

其中扩容的操作是:

(1)创建一个新的hash表,长度为原表的两倍,然后将oldtable的数据拷贝到新表中。那怎么拷贝呢?

(2)因为拷贝到新表,hash值需要重新计算,key的hash和新表的length-1进行计算,然后插入到新表中,如果hash桶存在链表,则使用头插入的方式,插入到新表中。这会导致数据在新表中是倒置的。如下图所示:

(3)将新表赋值给table

头插入法导致的并发问题:

此时头插入方法会导致链表死循环,具体过程是如下:

(1)当并发情况下,假设T1和T2都并发put,并且都符合扩容的条件,对其进行相应扩容,如下图所示,当程序执行到 Entry<K,V> next = e.next;  时候,T2休息,T1继续执行直到扩容结束。

(2)T1结束之后,T2被唤醒,由于是new出来的新对象,对于T2而言也是一个新的数组,然后对A插入到头结点,接着B插入到头节点,然后执行新表中的A,由于table中的B在上述T1中已经指向了A,所以按照resize代码的头插入法,A的next肯定指向新表中的B,此时在新表中陷入了死循环。

1.2 get方法

get方法还是很简单,通过key的hash获取到hash表中的位置,然后遍历其列表,通过比较key,如果相等则返回其entry对象。

  1. final Entry<K,V> getEntry(Object key) {
  2. ......
  3. int hash = (key == null) ? 0 : hash(key);
  4. for (Entry<K,V> e = table[hash&(table.length-1)];//得到冲突链表
  5. e != null; e = e.next) {//依次遍历冲突链表中的每个entry
  6. Object k;
  7. //依据equals()方法判断是否相等
  8. if (e.hash == hash &&
  9. ((k = e.key) == key || (key != null && key.equals(k))))
  10. return e;
  11. }
  12. return null;
  13. }

2、1.8版本的底层实现

1.8版本增加了红黑树,当链表个数大于8个时,会生成红黑树,当相同的hash个数小于6个时,红黑树也会退化成链表

2.1 put方法

(1)计算相应key的hash,然后hash&table.length-1,获取在数组中桶的位置,如果为空则直接new Node插入即可。

(2)如果table[i] != null。则判断此key是否相等,如果相等,则更新老的值

(3)如果table[i]是树节点,将此节点插入到树中

(4)如果table[i]是链表,则遍历链表,如果链表找到,则更新老的值,如果没有找到则使用尾插入插入其节点,插入之后,当节点个数大于8个,则转换成红黑树

(5)插入之后,查看size是否大于阈值,如果符合则resize。

  1. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
  2. boolean evict) {
  3. Node<K,V>[] tab; Node<K,V> p; int n, i;
  4. if ((tab = table) == null || (n = tab.length) == 0)
  5. n = (tab = resize()).length;
  6. if ((p = tab[i = (n - 1) & hash]) == null)
  7. tab[i] = newNode(hash, key, value, null);
  8. else {
  9. Node<K,V> e; K k;
  10. if (p.hash == hash &&
  11. ((k = p.key) == key || (key != null && key.equals(k))))
  12. e = p;
  13. else if (p instanceof TreeNode)
  14. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  15. else {
  16. for (int binCount = 0; ; ++binCount) {
  17. if ((e = p.next) == null) {
  18. p.next = newNode(hash, key, value, null);
  19. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
  20. treeifyBin(tab, hash);
  21. break;
  22. }
  23. if (e.hash == hash &&
  24. ((k = e.key) == key || (key != null && key.equals(k))))
  25. break;
  26. p = e;
  27. }
  28. }
  29. if (e != null) { // existing mapping for key
  30. V oldValue = e.value;
  31. if (!onlyIfAbsent || oldValue == null)
  32. e.value = value;
  33. afterNodeAccess(e);
  34. return oldValue;
  35. }
  36. }
  37. ++modCount;
  38. if (++size > threshold)
  39. resize();
  40. afterNodeInsertion(evict);
  41. return null;
  42. }

2.2 扩容方法

(1)肯定也会创建一个新表,这是新表直接赋值给了了table,此时会存在一个并发问题,当扩容时,如果此时有一个线程get查询此table数组,则查询不到相应的数据。

(2)遍历oldtable,然后将数据迁移到新表中。遍历桶中如果只有一个节点,则直接通过hash计算到新表中桶的位置,赋值即可

(3)如果此节点是树节点,直接迁移此树到新表中

(4)如果此节点为链表,此时有一个知识点,新表的长度为老表中的2倍,相当于2进制中的高位为1,也就是说链表中hash的二进制高位为1 的放到j+oldCap中,高位为0的则放到j中,并且是顺序放置。

  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. if (oldCap > 0) {
  7. if (oldCap >= MAXIMUM_CAPACITY) {
  8. threshold = Integer.MAX_VALUE;
  9. return oldTab;
  10. }
  11. else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
  12. oldCap >= DEFAULT_INITIAL_CAPACITY)
  13. newThr = oldThr << 1; // double threshold
  14. }
  15. else if (oldThr > 0) // initial capacity was placed in threshold
  16. newCap = oldThr;
  17. else { // zero initial threshold signifies using defaults
  18. newCap = DEFAULT_INITIAL_CAPACITY;
  19. newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
  20. }
  21. if (newThr == 0) {
  22. float ft = (float)newCap * loadFactor;
  23. newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
  24. (int)ft : Integer.MAX_VALUE);
  25. }
  26. threshold = newThr;
  27. @SuppressWarnings({"rawtypes","unchecked"})
  28. Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
  29. table = newTab;
  30. if (oldTab != null) {
  31. for (int j = 0; j < oldCap; ++j) {
  32. Node<K,V> e;
  33. if ((e = oldTab[j]) != null) {
  34. oldTab[j] = null;
  35. if (e.next == null)
  36. newTab[e.hash & (newCap - 1)] = e;
  37. else if (e instanceof TreeNode)
  38. ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
  39. else { // preserve order
  40. Node<K,V> loHead = null, loTail = null;
  41. Node<K,V> hiHead = null, hiTail = null;
  42. Node<K,V> next;
  43. do {
  44. next = e.next;
  45. if ((e.hash & oldCap) == 0) {
  46. if (loTail == null)
  47. loHead = e;
  48. else
  49. loTail.next = e;
  50. loTail = e;
  51. }
  52. else {
  53. if (hiTail == null)
  54. hiHead = e;
  55. else
  56. hiTail.next = e;
  57. hiTail = e;
  58. }
  59. } while ((e = next) != null);
  60. if (loTail != null) {
  61. loTail.next = null;
  62. newTab[j] = loHead;
  63. }
  64. if (hiTail != null) {
  65. hiTail.next = null;
  66. newTab[j + oldCap] = hiHead;
  67. }
  68. }
  69. }
  70. }
  71. }
  72. return newTab;
  73. }

2.3 get方法

get方法就比1.7多了一步在树中查询

  1. final Node<K,V> getNode(int hash, Object key) {
  2. Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
  3. if ((tab = table) != null && (n = tab.length) > 0 &&
  4. (first = tab[(n - 1) & hash]) != null) {
  5. if (first.hash == hash && // always check first node
  6. ((k = first.key) == key || (key != null && key.equals(k))))
  7. return first;
  8. if ((e = first.next) != null) {
  9. if (first instanceof TreeNode)
  10. return ((TreeNode<K,V>)first).getTreeNode(hash, key);
  11. do {
  12. if (e.hash == hash &&
  13. ((k = e.key) == key || (key != null && key.equals(k))))
  14. return e;
  15. } while ((e = e.next) != null);
  16. }
  17. }
  18. return null;
  19. }

总结1.7和1.8的区别:

1、结构不一致,1.7是数组+链表,1.8是数组+链表+红黑树

2、扩容时机,1.7是在扩容之后插入的数据,1.8是插入之后进行扩容

3、插入方式不一样,1.7是头插入方法,使得链表数据在新表中是倒置的,1.8则是尾插入法,使得在新表中的数据是和老表中的插入顺序是一致的

4、并发问题,1.7 头插入方法会导致在并发的时候死循环,1.8解决了此问题,使用尾插入方法,但是在扩容的时候先对table进行赋值,使得并发get的时候,获取到空值。1.7在并发put的时候,如果一个线程在扩容,由于table不具备可见性,所以另一个线程对table进行插入数据后,第一个线程会将新表覆盖老表,而第二个线程在老表插入的数据则会丢失。1.8也解决了此问题,现在HashMap会在扩容时确保所有线程都看到的是最新的数据副本,即使有线程在执行扩容操作。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/971086
推荐阅读
相关标签
  

闽ICP备14008679号