有人说HashMap是jdk中最难的类,重要性不用多说了,敲过代码的应该都懂,那么一起啃下这个硬骨头吧!

一、哈希表

在了解HashMap之前,先看看啥是哈希表,首先回顾下数组以及链表
数组:采用一段连续的存储单元来存储数据。对于指定下标的查找,时间复杂度为O(1);通过给定值进行查找,需要遍历数组,逐一比对给定关键字和数组元素,时间复杂度为O(n),当然,对于有序数组,则可采用二分查找,插值查找,斐波那契查找等方式,可将查找复杂度提高为O(logn);对于一般的插入删除操作,涉及到数组元素的移动,其平均复杂度也为O(n)。
线性链表:对于链表的新增,删除等操作(在找到指定操作位置后),仅需处理结点间的引用即可,时间复杂度为O(1),而查找操作需要遍历链表逐一进行比对,复杂度为O(n)。
哈希表:相比上述几种数据结构,在哈希表中进行添加,删除,查找等操作,性能十分之高,不考虑哈希冲突的情况下,仅需一次定位即可完成,时间复杂度为O(1)。
数组查询快的一个主要原因就是每个元素都有对应的index,根据index可以很方便的取数,哈希表的主干则是使用数组结构。来个图:

当插入数据时,首先对要插入的数据进行哈希计算(哈希算法可以说直接影响哈希表性能),得到某个值,这个值也就是代表数据在哈希表中的存储位置。举个例子,当前哈希表的长度为6,那么对于任何的正整数%6,得到的结果肯定是0-5,这小学数学应该就懂了吧!然后将余数作为要插入的位置,进行数据的保存。那就会有人问了,如果不同数据插入时,计算得到的余数相同怎么办?非常好,这就是哈希冲突,或是哈希碰撞。

二、hash冲突(hash碰撞)

哈希冲突的解决方案有多种:开放定址法(发生冲突,继续寻找下一块未被占用的存储地址),再散列函数法,链地址法,而HashMap即是采用了链地址法,也就是数组+链表的方式。

对于HashMap来说,如果没有出现hash冲突,自然是最好的,找到对应位置直接插入即可;若是存在hash冲突,由于每个位置上存在的其实是链表,往当前链表上加数据。

在jdk1.8之前,hashmap图示如下:

在1.8中,如图:

bucket代表的是桶,也就是当某一个位置上面的节点数大于8时,采用红黑树,否则使用链表。

jdk1.8之前的hashmap都采用上图的结构,都是基于一个数组和多个单链表,hash值冲突的时候,就将对应节点以链表的形式存储。如果在一个链表中查找其中一个节点时,将会花费O(n)的查找时间,会有很大的性能损失。到了jdk1.8,当同一个hash值的节点数不小于8时,不再采用单链表形式存储,而是采用红黑树。

三、类定义、成员变量、构造函数

1、类定义

  1. public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable

2、成员变量

  1. private static final long serialVersionUID = 362498820763181265L;
  2. //初始化容量。左位移4位,也就是2的四次方
  3. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  4. //最大容量
  5. static final int MAXIMUM_CAPACITY = 1 << 30;
  6. //加载因子
  7. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  8. //当桶(bucket)上的结点数大于这个值时会转成红黑树
  9. static final int TREEIFY_THRESHOLD = 8;
  10. //当桶(bucket)上的结点数小于这个值时树转链表
  11. static final int UNTREEIFY_THRESHOLD = 6;
  12. //桶中结构转化为红黑树对应的table的最小大小
  13. static final int MIN_TREEIFY_CAPACITY = 64;
  14. //存储元素的数组,总是2的幂次倍
  15. transient Node<K,V>[] table;
  16. //存在所有的entry
  17. transient Set<Map.Entry<K,V>> entrySet;
  18. //实际存储的键值对的个数,不等于数组的size
  19. transient int size;
  20. //修改次数
  21. transient int modCount;
  22. //临界值,当实际大小(容量*填充因子)超过临界值时,会进行扩容
  23. int threshold;
  24. //负载因子,代表了table的填充度有多少,默认是0.75
  25. final float loadFactor;

3、构造函数

  1. public HashMap(int initialCapacity, float loadFactor) {
  2. if (initialCapacity < 0)
  3. throw new IllegalArgumentException("Illegal initial capacity: " +
  4. initialCapacity);
  5. //容量不能大于hashMap允许的最大值,超过了不会报错,默认最大值
  6. if (initialCapacity > MAXIMUM_CAPACITY)
  7. initialCapacity = MAXIMUM_CAPACITY;
  8. //负载因子不能<=0,不能为非数字
  9. if (loadFactor <= 0 || Float.isNaN(loadFactor))
  10. throw new IllegalArgumentException("Illegal load factor: " +
  11. loadFactor);
  12. this.loadFactor = loadFactor;
  13. //这个方法返回大于initialCapacity的最小的二次幂数值。
  14. this.threshold = tableSizeFor(initialCapacity);
  15. }
  16. public HashMap(int initialCapacity) {
  17. this(initialCapacity, DEFAULT_LOAD_FACTOR);
  18. }
  19. public HashMap() {
  20. this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
  21. }
  22. public HashMap(Map<? extends K, ? extends V> m) {
  23. this.loadFactor = DEFAULT_LOAD_FACTOR;
  24. //将m的所有元素存入本HashMap实例中。
  25. putMapEntries(m, false);
  26. }

四、内部类

1、Node

  1. static class Node<K,V> implements Map.Entry<K,V> {
  2. final int hash;
  3. final K key;
  4. V value;
  5. Node<K,V> next;
  6.  
  7. Node(int hash, K key, V value, Node<K,V> next) {
  8. this.hash = hash;
  9. this.key = key;
  10. this.value = value;
  11. this.next = next;
  12. }
  13.  
  14. public final K getKey() { return key; }
  15. public final V getValue() { return value; }
  16. public final String toString() { return key + "=" + value; }
  17.  
  18. public final int hashCode() {
  19. return Objects.hashCode(key) ^ Objects.hashCode(value);
  20. }
  21.  
  22. public final V setValue(V newValue) {
  23. V oldValue = value;
  24. value = newValue;
  25. return oldValue;
  26. }
  27.  
  28. public final boolean equals(Object o) {
  29. if (o == this)
  30. return true;
  31. if (o instanceof Map.Entry) {
  32. Map.Entry<?,?> e = (Map.Entry<?,?>)o;
  33. if (Objects.equals(key, e.getKey()) &&
  34. Objects.equals(value, e.getValue()))
  35. return true;
  36. }
  37. return false;
  38. }
  39. }

2、keySet

  1. final class KeySet extends AbstractSet<K> {
  2. public final int size() { return size; }
  3. public final void clear() { HashMap.this.clear(); }
  4. public final Iterator<K> iterator() { return new KeyIterator(); }
  5. public final boolean contains(Object o) { return containsKey(o); }
  6. public final boolean remove(Object key) {
  7. return removeNode(hash(key), key, null, false, true) != null;
  8. }
  9. public final Spliterator<K> spliterator() {
  10. return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
  11. }
  12. public final void forEach(Consumer<? super K> action) {
  13. Node<K,V>[] tab;
  14. if (action == null)
  15. throw new NullPointerException();
  16. if (size > 0 && (tab = table) != null) {
  17. int mc = modCount;
  18. for (int i = 0; i < tab.length; ++i) {
  19. for (Node<K,V> e = tab[i]; e != null; e = e.next)
  20. action.accept(e.key);
  21. }
  22. if (modCount != mc)
  23. throw new ConcurrentModificationException();
  24. }
  25. }
  26. }

3、Values

  1. final class Values extends AbstractCollection<V> {
  2. public final int size() { return size; }
  3. public final void clear() { HashMap.this.clear(); }
  4. public final Iterator<V> iterator() { return new ValueIterator(); }
  5. public final boolean contains(Object o) { return containsValue(o); }
  6. public final Spliterator<V> spliterator() {
  7. return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
  8. }
  9. public final void forEach(Consumer<? super V> action) {
  10. Node<K,V>[] tab;
  11. if (action == null)
  12. throw new NullPointerException();
  13. if (size > 0 && (tab = table) != null) {
  14. int mc = modCount;
  15. for (int i = 0; i < tab.length; ++i) {
  16. for (Node<K,V> e = tab[i]; e != null; e = e.next)
  17. action.accept(e.value);
  18. }
  19. if (modCount != mc)
  20. throw new ConcurrentModificationException();
  21. }
  22. }
  23. }

4、entrySet

  1. final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
  2. public final int size() { return size; }
  3. public final void clear() { HashMap.this.clear(); }
  4. public final Iterator<Map.Entry<K,V>> iterator() {
  5. return new EntryIterator();
  6. }
  7. public final boolean contains(Object o) {
  8. if (!(o instanceof Map.Entry))
  9. return false;
  10. Map.Entry<?,?> e = (Map.Entry<?,?>) o;
  11. Object key = e.getKey();
  12. Node<K,V> candidate = getNode(hash(key), key);
  13. return candidate != null && candidate.equals(e);
  14. }
  15. public final boolean remove(Object o) {
  16. if (o instanceof Map.Entry) {
  17. Map.Entry<?,?> e = (Map.Entry<?,?>) o;
  18. Object key = e.getKey();
  19. Object value = e.getValue();
  20. return removeNode(hash(key), key, value, true, true) != null;
  21. }
  22. return false;
  23. }
  24. public final Spliterator<Map.Entry<K,V>> spliterator() {
  25. return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
  26. }
  27. public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
  28. Node<K,V>[] tab;
  29. if (action == null)
  30. throw new NullPointerException();
  31. if (size > 0 && (tab = table) != null) {
  32. int mc = modCount;
  33. for (int i = 0; i < tab.length; ++i) {
  34. for (Node<K,V> e = tab[i]; e != null; e = e.next)
  35. action.accept(e);
  36. }
  37. if (modCount != mc)
  38. throw new ConcurrentModificationException();
  39. }
  40. }
  41. }

5、红黑树

  1. //红黑树
  2. static final class TreeNode<k,v> extends LinkedHashMap.Entry<k,v> {
  3. TreeNode<k,v> parent; // 父节点
  4. TreeNode<k,v> left; //左子树
  5. TreeNode<k,v> right;//右子树
  6. TreeNode<k,v> prev; // needed to unlink next upon deletion
  7. boolean red; //颜色属性
  8. TreeNode(int hash, K key, V val, Node<k,v> next) {
  9. super(hash, key, val, next);
  10. }
  11.  
  12. //返回当前节点的根节点
  13. final TreeNode<k,v> root() {
  14. for (TreeNode<k,v> r = this, p;;) {
  15. if ((p = r.parent) == null)
  16. return r;
  17. r = p;
  18. }
  19. }
  20. }

红黑树比链表多了四个变量,parent父节点、left左节点、right右节点、prev上一个同级节点,红黑树内容较多,不在赘述。

五、主要方法

1、put()

  1. //这个自然是用的最多的方法之一
  2. public V put(K key, V value) {
  3. return putVal(hash(key), key, value, false, true);
  4. }
  5. static final int hash(Object key) {
  6. int h;
  7. //如果key为null,hash值为0.不为null,获取key的hashcode(),然后将h无符号右位移16位,再与原来的h做异或运算。
  8. //为啥这么弄?鬼知道。。。但是目的就是为了让散列均匀
  9. return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  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. //如果table为null或者长度为0,首先进行扩容。
  15. if ((tab = table) == null || (n = tab.length) == 0)
  16. n = (tab = resize()).length;
  17. //(n-1)&hash是啥意思呢?目的:获取该对象的键在hashmap中的位置。n表示的是hash桶数组的长度,并且该长度为2的n次方,这样(n-1)&hash就等价于hash%n。因为&运算的效率高于%运算。(n-1)&hash=hash%n有一个前提,就是n为2的次方,比如2、4、8。。。
  18. 如果当前位置为null,说明还没有元素被放在这个位置,所以直接new一个node,放在此位置即可。
  19. if ((p = tab[i = (n - 1) & hash]) == null)
  20. //newNode就是new一个node,放入到当前数组的对应位置上。
  21. tab[i] = newNode(hash, key, value, null);
  22. else {
  23. Node<K,V> e; K k;
  24. //当前位置已经有node了,也就是出现了hash冲突
  25. //如果桶中的第一个元素(数组中的结点)的hash值相等,key相等。
  26. if (p.hash == hash &&
  27. //判断Key是否与当前存在的node的key值相等
  28. ((k = p.key) == key || (key != null && key.equals(k))))
  29. e = p;
  30. //判断该链是红黑树
  31. else if (p instanceof TreeNode)
  32. //放入红黑树中
  33. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  34. //不是红黑树,肯定就是链表了
  35. else {
  36. //在链表的最末端插入节点
  37. for (int binCount = 0; ; ++binCount) {
  38. //如果当前node的next为null,说明当前的节点就是链表的最后一个元素
  39. if ((e = p.next) == null) {
  40. p.next = newNode(hash, key, value, null);
  41. //因为bidCount从0开始,所以判断的值为TREEIFY_THRESHOLD - 1,大于TREEIFY_THRESHOLD,转换成红黑树
  42. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
  43. treeifyBin(tab, hash);
  44. break;
  45. }
  46. //判断链表中结点的key值与插入的元素的key值是否相等。如果有相等的直接跳出循环
  47. if (e.hash == hash &&
  48. ((k = e.key) == key || (key != null && key.equals(k))))
  49. break;
  50. p = e;
  51. }
  52. }
  53. //表示在桶中找到key值、hash值与插入元素相等的结点
  54. if (e != null) { // existing mapping for key
  55. V oldValue = e.value;
  56. if (!onlyIfAbsent || oldValue == null)
  57. e.value = value;
  58. afterNodeAccess(e);
  59. return oldValue;
  60. }
  61. }
  62. ++modCount;
  63. if (++size > threshold)
  64. resize();
  65. afterNodeInsertion(evict);
  66. return null;
  67. }

总结下putVal(),如下:

  • ①.判断键值对数组table[i]是否为空或为null,否则执行resize()进行扩容;
  • ②.根据键值key计算hash值得到插入的数组索引i,如果table[i]==null,直接新建节点添加,转向⑥,如果table[i]不为空,转向③;
  • ③.判断table[i]的首个元素是否和key一样,如果相同直接覆盖value,否则转向④,这里的相同指的是hashCode以及equals;
  • ④.判断table[i] 是否为treeNode,即table[i] 是否是红黑树,如果是红黑树,则直接在树中插入键值对,否则转向⑤;
  • ⑤.遍历table[i],判断链表长度是否大于8,大于8的话把链表转换为红黑树,在红黑树中执行插入操作,否则进行链表的插入操作;遍历过程中若发现key已经存在直接覆盖value即可;
  • ⑥.插入成功后,判断实际存在的键值对数量size是否超多了最大容量threshold,如果超过,进行扩容。

HashMap的数据存储实现原理

流程:

1. 根据key计算得到key.hash = (h = k.hashCode()) ^ (h >>> 16);

2. 根据key.hash计算得到桶数组的索引index = key.hash & (table.length - 1),这样就找到该key的存放位置了:

  • ① 如果该位置没有数据,用该数据新生成一个节点保存新数据,返回null;
  • ② 如果该位置有数据是一个红黑树,那么执行相应的插入 / 更新操作;
  • ③ 如果该位置有数据是一个链表,分两种情况一是该链表没有这个节点,另一个是该链表上有这个节点,注意这里判断的依据是key.hash是否一样:

如果该链表没有这个节点,那么采用尾插法新增节点保存新数据,返回null;如果该链表已经有这个节点了,那么找到该节点并更新新数据,返回老数据。

注意:

HashMap的put会返回key的上一次保存的数据,比如:

  1. HashMap<String, String> map = new HashMap<String, String>();
  2. System.out.println(map.put("a", "A")); // 打印null
  3. System.out.println(map.put("a", "AA")); // 打印A
  4. System.out.println(map.put("a", "AB")); // 打印AA

2、get()

  1. //get(key)方法的本质就是根据key值获取到对应的节点,然后将Node的value返回
  2. public V get(Object key) {
  3. Node<K,V> e;
  4. return (e = getNode(hash(key), key)) == null ? null : e.value;
  5. }
  6. final Node<K,V> getNode(int hash, Object key) {
  7. Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
  8. if ((tab = table) != null && (n = tab.length) > 0 &&
  9. //在hashMap里,(n - 1) & hash = hash % n。证明方法:https://blog.csdn.net/evilcry2012/article/details/88823910
  10. (first = tab[(n - 1) & hash]) != null) {
  11. if (first.hash == hash && // always check first node
  12. ((k = first.key) == key || (key != null && key.equals(k))))
  13. return first;
  14. //链中的第一个节点不符合规定,继续往下找。
  15. if ((e = first.next) != null) {
  16. //如果是红黑树的话,查询红黑树的节点,然后返回。红黑树由于本人还不是非常清楚,所以暂不做解释了
  17. if (first instanceof TreeNode)
  18. return ((TreeNode<K,V>)first).getTreeNode(hash, key);
  19. do {
  20. //这时候就确定为链表结构的数据了,轻车熟路,不多解释了。不清楚的可以看看本人的LinkedList
  21. if (e.hash == hash &&
  22. ((k = e.key) == key || (key != null && key.equals(k))))
  23. return e;
  24. } while ((e = e.next) != null);
  25. }
  26. }
  27. return null;
  28. }

3 、remove()

  1. // HashMap 中实现
  2. public V remove(Object key) {
  3. Node<K,V> e;
  4. return (e = removeNode(hash(key), key, null, false, true)) == null ?
  5. null : e.value;
  6. }
  7.  
  8. // HashMap 中实现
  9. final Node<K,V> removeNode(int hash, Object key, Object value,
  10. boolean matchValue, boolean movable) {
  11. Node<K,V>[] tab; Node<K,V> p; int n, index;
  12. if ((tab = table) != null && (n = tab.length) > 0 &&
  13. (p = tab[index = (n - 1) & hash]) != null) {
  14. Node<K,V> node = null, e; K k; V v;
  15. if (p.hash == hash &&
  16. ((k = p.key) == key || (key != null && key.equals(k))))
  17. node = p;
  18. else if ((e = p.next) != null) {
  19. if (p instanceof TreeNode) {...}
  20. else {
  21. // 遍历单链表,寻找要删除的节点,并赋值给 node 变量
  22. do {
  23. if (e.hash == hash &&
  24. ((k = e.key) == key ||
  25. (key != null && key.equals(k)))) {
  26. node = e;
  27. break;
  28. }
  29. p = e;
  30. } while ((e = e.next) != null);
  31. }
  32. }
  33. if (node != null && (!matchValue || (v = node.value) == value ||
  34. (value != null && value.equals(v)))) {
  35. if (node instanceof TreeNode) {...}
  36. // 将要删除的节点从单链表中移除
  37. else if (node == p)
  38. tab[index] = node.next;
  39. else
  40. p.next = node.next;
  41. ++modCount;
  42. --size;
  43. afterNodeRemoval(node); // 调用删除回调方法进行后续操作
  44. return node;
  45. }
  46. }
  47. return null;
  48. }
  49. void afterNodeRemoval(Node<K,V> p) { }

4、 resize()

  • ①.在jdk1.8中,resize方法是在hashmap中的键值对大于阀值时或者初始化时,就调用resize方法进行扩容;
  • ②.每次扩展的时候,都是扩展2倍;
  • ③.扩展后Node对象的位置要么在原位置,要么移动到原偏移量两倍的位置。

HashMap扩容可以分为三种情况:

第一种:使用默认构造方法初始化HashMap。从前文可以知道HashMap在一开始初始化的时候会返回一个空的table,并且thershold为0。因此第一次扩容的容量为默认值DEFAULT_INITIAL_CAPACITY也就是16。同时threshold = DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR = 12。

第二种:指定初始容量的构造方法初始化HashMap。那么从下面源码可以看到初始容量会等于threshold,接着threshold = 当前的容量(threshold) * DEFAULT_LOAD_FACTOR。

第三种:HashMap不是第一次扩容。如果HashMap已经扩容过的话,那么每次table的容量以及threshold量为原有的两倍。

  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. * @return the table
  8. *
  9. *
  10. *
  11. * 初始化或者翻倍表大小。
  12. * 如果表为null,则根据存放在threshold变量中的初始化capacity的值来分配table内存
  13. * (这个注释说的很清楚,在实例化HashMap时,capacity其实是存放在了成员变量threshold中,
  14. * 注意,HashMap中没有capacity这个成员变量)
  15. * 。如果表不为null,由于我们使用2的幂来扩容,
  16. * 则每个bin元素要么还是在原来的bucket中,要么在2的幂中
  17. *
  18. * 此方法功能:初始化或扩容
  19. */
  20. final Node<K,V>[] resize() {
  21. Node<K,V>[] oldTab = table;
  22. int oldCap = (oldTab == null) ? 0 : oldTab.length;
  23. int oldThr = threshold;
  24. //新的容量值,新的扩容阀界值
  25. int newCap, newThr = 0;
  26. //oldTab!=null,则oldCap>0
  27. if (oldCap > 0) {
  28. //如果此时oldCap>=MAXIMUM_CAPACITY(1 << 30),表示已经到了最大容量,这时还要往map中放数据,则阈值设置为整数的最大值 Integer.MAX_VALUE,直接返回这个oldTab的内存地址。
  29. if (oldCap >= MAXIMUM_CAPACITY) {
  30. threshold = Integer.MAX_VALUE;
  31. return oldTab;
  32. }
  33. //如果(当前容量*2<最大容量&&当前容量>=默认初始化容量(16))
  34. //并将将原容量值<<1(相当于*2)赋值给 newCap
  35. else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
  36. oldCap >= DEFAULT_INITIAL_CAPACITY)
  37. //如果能进来证明此map是扩容而不是初始化
  38. //操作:将原扩容阀界值<<1(相当于*2)赋值给 newThr
  39. newThr = oldThr << 1; // double threshold
  40. }
  41. else if (oldThr > 0) // initial capacity was placed in threshold
  42. //进入此if证明创建map时用的带参构造:public HashMap(int initialCapacity)或 public HashMap(int initialCapacity, float loadFactor)
  43. //注:带参的构造中initialCapacity(初始容量值)不管是输入几都会通过 “this.threshold = tableSizeFor(initialCapacity);”此方法计算出接近initialCapacity参数的2^n来作为初始化容量(初始化容量==oldThr)
  44. newCap = oldThr;
  45. else { // zero initial threshold signifies using defaults
  46. //进入此if证明创建map时用的无参构造:
  47. //然后将参数newCap(新的容量)、newThr(新的扩容阀界值)进行初始化
  48. newCap = DEFAULT_INITIAL_CAPACITY;
  49. newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
  50. }
  51. if (newThr == 0) {
  52.  
  53. //进入此if有两种可能
  54. // 第一种:进入此“if (oldCap > 0)”中且不满足该if中的两个if
  55. // 第二种:进入这个“else if (oldThr > 0)”
  56.  
  57. //分析:进入此if证明该map在创建时用的带参构造,如果是第一种情况就说明是进行扩容且oldCap(旧容量)小于16,如果是第二种说明是第一次put
  58. float ft = (float)newCap * loadFactor;
  59. //计算扩容阀界值
  60. newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
  61. (int)ft : Integer.MAX_VALUE);
  62. }
  63. threshold = newThr;
  64. @SuppressWarnings({"rawtypes","unchecked"})
  65. Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
  66. table = newTab;
  67. //如果“oldTab != null”说明是扩容,否则直接返回newTab
  68. if (oldTab != null) {
  69. for (int j = 0; j < oldCap; ++j) {
  70. Node<K,V> e;
  71. if ((e = oldTab[j]) != null) {
  72. oldTab[j] = null;
  73.  
  74. if (e.next == null)
  75. newTab[e.hash & (newCap - 1)] = e;
  76. else if (e instanceof TreeNode)
  77. //如果该元素是TreeNode的实例
  78. ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
  79. else { // preserve order
  80. Node<K,V> loHead = null, loTail = null;//此对象接收会放在原来位置
  81. Node<K,V> hiHead = null, hiTail = null;//此对象接收会放在“j + oldCap”(当前位置索引+原容量的值)
  82. Node<K,V> next;
  83. do {
  84. next = e.next;
  85. //以下是扩容操作的核心,详情见我的博客:https://www.cnblogs.com/shianliang/p/9204942.html
  86. if ((e.hash & oldCap) == 0) {
  87.  
  88. if (loTail == null)
  89. loHead = e;
  90. else
  91. loTail.next = e;
  92. loTail = e;
  93. }
  94. else {
  95. if (hiTail == null)
  96. hiHead = e;
  97. else
  98. hiTail.next = e;
  99. hiTail = e;
  100. }
  101. } while ((e = next) != null);
  102. if (loTail != null) {
  103. loTail.next = null;
  104. newTab[j] = loHead;
  105. }
  106. if (hiTail != null) {
  107. hiTail.next = null;
  108. newTab[j + oldCap] = hiHead;
  109. }
  110. }
  111. }
  112. }
  113. }
  114. return newTab;
  115. }

六、思考点

1、为啥HashMap的初始大小为16?并且每次自动扩展或是手动初始化,长度必须为2的幂?

用16当做初始化的数,主要是考虑到key映射到index的hash算法。例如index = Hash("apple"),hash运算要尽量分布均匀,最理想的效果就是在一个hashMap对象put操作时,永远不要有hash冲突,当然一般实现不了。有一种最简单hash运算就是拿hash%length,余数为0~length-1,这种方式可以实现,但是需要把十进制的数转成二进制,效率相对较慢。在jdk8中,jdk大神是这么干的,index = HashCode(Key)&(Length - 1),具体的原因可以看这篇博客:https://blog.csdn.net/evilcry2012/article/details/88823910

2、高并发环境,hashMap可能会出现死锁

可以看下这篇文章:高并发下的HashMap

走进JDK(十)------HashMap的更多相关文章

  1. 走进JDK(十二)------TreeMap

    一.类定义 TreeMap的类结构: public class TreeMap<K,V> extends AbstractMap<K,V> implements Navigab ...

  2. 调试过程中发现按f5无法走进jdk源码

    debug 模式 ,在fis=new FileInputStream(file); 行打断点 调试过程中发现按f5无法走进jdk源码 package com.lzl.spring.test; impo ...

  3. java多线程:并发包中ConcurrentHashMap和jdk的HashMap的对比

    一:HashMap--->底层存储的是Entry<K,V>[]数组--->Entry<K,V>的结构是一个单向的链表static class Entry<K, ...

  4. Java进阶知识点:不要只会写synchronized - JDK十大并发编程组件总结

    一.背景 提到Java中的并发编程,首先想到的便是使用synchronized代码块,保证代码块在并发环境下有序执行,从而避免冲突.如果涉及多线程间通信,可以再在synchronized代码块中使用w ...

  5. Java进阶知识点7:不要只会写synchronized - JDK十大并发编程组件总结

    一.背景 提到Java中的并发编程,首先想到的便是使用synchronized代码块,保证代码块在并发环境下有序执行,从而避免冲突.如果涉及多线程间通信,可以再在synchronized代码块中使用w ...

  6. java jdk 中HashMap的源码解读

    HashMap是我们在日常写代码时最常用到的一个数据结构,它为我们提供key-value形式的数据存储.同时,它的查询,插入效率都非常高. 在之前的排序算法总结里面里,我大致学习了HashMap的实现 ...

  7. jdk 8 HashMap源码解读

    转自:https://www.cnblogs.com/little-fly/p/7344285.html 在原来的作者的基础上,增加了本人对源代码的一些解读. 如有侵权,请联系本人 这几天学习了Has ...

  8. 走进JDK(十一)------LinkedHashMap

    概述LinkedHashMap 继承自 HashMap,在 HashMap 基础上,通过维护一条双向链表,解决了 HashMap 不能随时保持遍历顺序和插入顺序一致的问题.除此之外,LinkedHas ...

  9. 走进JDK(二)------String

    本文基于java8. 基本概念: Jvm 内存中 String 的表示是采用 unicode 编码 UTF-8 是 Unicode 的实现方式之一 一.String定义 public final cl ...

随机推荐

  1. 高阶函数map_reduce_sorted_filter

    能够把函数当成参数传递的参数就是高阶函数 map map: 功能: 拿iterable的每一个元素放入func中, func的返回值放入迭代器内进行返回 参数: iterable, func 返回: ...

  2. Hibernate工作原理及为什么要用?

    1.原理: 1.读取并解析配置文件    new Configuration().configure()2.读取并解析映射信息,创建SessionFactory    sf=buildSessionF ...

  3. 保持ssh连接长时间不断开的技巧

    我经常用ssh连接服务器,过段时间不用, 需要恢复一下断开的连接, 原因是NAT防火墙喜欢对空闲的会话进行超时处理,以确保它们状态表的干净和内存的低占用率,因为 长时间保持连接, 会长期占用部分系统资 ...

  4. leetcode207

    拓扑排序问题. class Solution { public: bool canFinish(int numCourses, vector<pair<int, int>>&a ...

  5. js代码技巧

    1.js 中不常用的处理方法 //取整 parseInt(a,10); //Before Math.floor(a); //Before a>>0; //Before ~~a; //Aft ...

  6. DOM+position:relative+缓冲运动

    一.nodeType节点类型 nodeType==3  ->文本节点 nodeType==1  ->元素节点 for(var i=0;i<oUl.childNodes.length; ...

  7. 思维导图-mysql log

  8. springmvc controller方法返回值

  9. Django中的class Meta

    元数据 class Meta做为嵌套类,主要目的是给上级类添加一些功能,或者指定一些标准 # 格式化  将返回的结果自定义 def __str__(self) rerurn self.username ...

  10. SpringJDBC中jdbcTemplate 的使用

    一:定义 SpringJDBC是spring官方提供的一个持久层框架,对JDBC进行了封装,提供了一个JDBCTemplated对象简化JDBC的开发.但Spring本身不是一个orm框架,与hibe ...