1.7的hashMap

学习hashMap具备的基础:位运算,集成,接口的实现,数据结构,数组+链表(红黑树)
https://www.bilibili.com/video/BV1H3411q7s7?p=8
拓展:左移相当于乘以2,右移除以2。
https://www.yuque.com/shier-tcmwp/notes/vb9f90
image.png

image.png
image.png
image.pngimage.png
image.pngimage.png


1.8的hashMap

资料来源:https://www.bilibili.com/video/BV1yX4y1w7ng?share_source=copy_web

  1. public class HashMap<K, V> extends AbstractMap<K, V>
  2. implements Map<K, V>, Cloneable, Serializable { // 1、实现了两个Map接口,重复--》多余
  3. // 3、属性部分
  4. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  5. final float loadFactor;
  6. // DEFAULT_INITIAL_CAPACITY.)
  7. int threshold;
  8. transient Node<K,V>[] table; // 底层数组
  9. // 2、 调用空构造器
  10. public HashMap() {
  11. this.loadFactor = DEFAULT_LOAD_FACTOR; // loadFactor = 0.75
  12. }
  13. // 4、调用有参构造器
  14. public HashMap(int initialCapacity) { //10
  15. this(initialCapacity, DEFAULT_LOAD_FACTOR); // this(10,0.75)
  16. }
  17. //5、跳到HashMap中
  18. public HashMap(int initialCapacity, float loadFactor) { // 10,0.75
  19. // 6、提高健壮性处理
  20. if (initialCapacity < 0)
  21. throw new IllegalArgumentException("Illegal initial capacity: " +
  22. initialCapacity);
  23. if (initialCapacity > MAXIMUM_CAPACITY)
  24. initialCapacity = MAXIMUM_CAPACITY;
  25. if (loadFactor <= 0 || Float.isNaN(loadFactor))
  26. throw new IllegalArgumentException("Illegal load factor: " +
  27. loadFactor);
  28. // 7、loadFactor = 0.75
  29. this.loadFactor = loadFactor;
  30. // 8、调用tableSizeFor方法,传入10
  31. this.threshold = tableSizeFor(initialCapacity);
  32. }
  33. /**
  34. * Returns a power of two size for the given target capacity.
  35. * 9、tableSizeFor---》确定主数组的长度 ---》返回的是最接近参数的2的n次幂 ----》10=》16 3=》4 6=》8
  36. */
  37. static final int tableSizeFor(int cap) { // 10
  38. int n = cap - 1;
  39. n |= n >>> 1;
  40. n |= n >>> 2;
  41. n |= n >>> 4;
  42. n |= n >>> 8;
  43. n |= n >>> 16;
  44. return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
  45. }
  46. // 10、调用put方法
  47. public V put(K key, V value) {\
  48. // 11、调用hash方法
  49. return putVal(hash(key), key, value, false, true);
  50. }
  51. // 12、hash方法,返回值就是hash码
  52. static final int hash(Object key) {
  53. int h;
  54. return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  55. }
  56. // 13、putVal方法
  57. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
  58. boolean evict) {
  59. Node<K,V>[] tab; Node<K,V> p; int n, i;
  60. if ((tab = table) == null || (n = tab.length) == 0)
  61. // 14、调用resize方法,该方法
  62. n = (tab = resize()).length;
  63. if ((p = tab[i = (n - 1) & hash]) == null)
  64. tab[i] = newNode(hash, key, value, null);
  65. else {
  66. Node<K,V> e; K k;
  67. if (p.hash == hash &&
  68. ((k = p.key) == key || (key != null && key.equals(k))))
  69. e = p;
  70. else if (p instanceof TreeNode)
  71. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  72. else {
  73. for (int binCount = 0; ; ++binCount) {
  74. if ((e = p.next) == null) {
  75. p.next = newNode(hash, key, value, null);
  76. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
  77. treeifyBin(tab, hash);
  78. break;
  79. }
  80. if (e.hash == hash &&
  81. ((k = e.key) == key || (key != null && key.equals(k))))
  82. break;
  83. p = e;
  84. }
  85. }
  86. if (e != null) { // existing mapping for key
  87. V oldValue = e.value;
  88. if (!onlyIfAbsent || oldValue == null)
  89. e.value = value;
  90. afterNodeAccess(e);
  91. return oldValue;
  92. }
  93. }
  94. ++modCount;
  95. if (++size > threshold)
  96. resize();
  97. afterNodeInsertion(evict);
  98. return null;
  99. }
  100. // 15、调用resize方法
  101. final Node<K,V>[] resize() {
  102. Node<K,V>[] oldTab = table;
  103. int oldCap = (oldTab == null) ? 0 : oldTab.length;
  104. int oldThr = threshold;
  105. int newCap, newThr = 0;
  106. if (oldCap > 0) {
  107. if (oldCap >= MAXIMUM_CAPACITY) {
  108. threshold = Integer.MAX_VALUE;
  109. return oldTab;
  110. }
  111. else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
  112. oldCap >= DEFAULT_INITIAL_CAPACITY)
  113. newThr = oldThr << 1; // double threshold
  114. }
  115. else if (oldThr > 0) // initial capacity was placed in threshold
  116. newCap = oldThr;
  117. else { // zero initial threshold signifies using defaults
  118. newCap = DEFAULT_INITIAL_CAPACITY;
  119. newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
  120. }
  121. if (newThr == 0) {
  122. float ft = (float)newCap * loadFactor;
  123. newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
  124. (int)ft : Integer.MAX_VALUE);
  125. }
  126. threshold = newThr;
  127. @SuppressWarnings({"rawtypes","unchecked"})
  128. Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
  129. // 16、resize方法从开始到这里都是确定table的大小。重要的地方是就是这里,table:底层的数组长度在这里确定了,为一个xxx长度的Node类型的数组
  130. table = newTab;
  131. if (oldTab != null) {
  132. for (int j = 0; j < oldCap; ++j) {
  133. Node<K,V> e;
  134. if ((e = oldTab[j]) != null) {
  135. oldTab[j] = null;
  136. if (e.next == null)
  137. newTab[e.hash & (newCap - 1)] = e;
  138. else if (e instanceof TreeNode)
  139. ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
  140. else { // preserve order
  141. Node<K,V> loHead = null, loTail = null;
  142. Node<K,V> hiHead = null, hiTail = null;
  143. Node<K,V> next;
  144. do {
  145. next = e.next;
  146. if ((e.hash & oldCap) == 0) {
  147. if (loTail == null)
  148. loHead = e;
  149. else
  150. loTail.next = e;
  151. loTail = e;
  152. }
  153. else {
  154. if (hiTail == null)
  155. hiHead = e;
  156. else
  157. hiTail.next = e;
  158. hiTail = e;
  159. }
  160. } while ((e = next) != null);
  161. if (loTail != null) {
  162. loTail.next = null;
  163. newTab[j] = loHead;
  164. }
  165. if (hiTail != null) {
  166. hiTail.next = null;
  167. newTab[j + oldCap] = hiHead;
  168. }
  169. }
  170. }
  171. }
  172. }
  173. return newTab;
  174. }
  175. }

经典面试题:
1、装填因子,装载因子,加载因子为什么要设置为0.75。
装填因子设置为1,空间利用率得到大大的提高,很容易发生碰撞,产生链表-》查询效率低
装填因子设置为0.5,空间利用率太低了,碰撞几率也低,产生链表低-》查询效率高。
所以取了一个折中的:0.75
2、主数组的长度为什么必须为2的n次方。
原因1:h & (length - 1)等效 h % length 操作,等效的前提是:length必须是2的整数倍。
原因2:防止哈希冲突,位置冲突。

  • 验证是整数倍:

length:8
hash :3 00000011
length-1 00000111
——————————————————与运算,相同为1,不同为0
00000011 —-》3 位置

hash :2 00000010
length-1 00000111
——————————————————
00000010 ——-》2位置

  • 验证不是整数倍:

length:9
hash :3 00000011
length-1 00001000
—————————————
00000000 ——》0位置

hash :2 00000010
length-1 00001000
—————————————————
00000000 ——》0位置

3、头插法为什么有循环问题