JDK1.8 HashMap源码分析

来源:互联网 发布:淘宝卖家商品采集软件 编辑:程序博客网 时间:2024/05/16 11:34

JDK1.8  HashMap源码分析

一、HashMap概述

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

下图中代表jdk1.8之前的hashmap结构,左边部分即代表哈希表,也称为哈希数组,数组的每个元素都是一个单链表的头节点,链表是用来解决冲突的,如果不同的key映射到了数组的同一位置处,就将其放入单链表中。(此图借用网上的图)


图一、jdk1.8之前hashmap结构图

 

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

图二、jdk1.8 hashmap结构图

二、重要的field

[java] view plain copy
  1. //table就是存储Node类的数组,就是对应上图中左边那一栏,  
  2.   /** 
  3.      * The table, initialized on first use, and resized as 
  4.      * necessary. When allocated, length is always a power of two. 
  5.      * (We also tolerate length zero in some operations to allow 
  6.      * bootstrapping mechanics that are currently not needed.) 
  7.   */  
  8. transient Node<K,V>[] table;  
  9.       
  10. /** 
  11.      * The number of key-value mappings contained in this map. 
  12. *  记录hashmap中存储键-值对的数量 
  13.   */  
  14. transient int size;  
  15.   
  16. /** 
  17.   * hashmap结构被改变的次数,fail-fast机制 
  18.   */  
  19. transient int modCount;  
  20.   
  21.     /** 
  22.      * The next size value at which to resize (capacity * load factor). 
  23.      * 扩容的门限值,当size大于这个值时,table数组进行扩容 
  24.      */  
  25.     int threshold;  
  26.   
  27.     /** 
  28.      * The load factor for the hash table. 
  29.      * 
  30.      */  
  31.  float loadFactor;  
  32. /** 
  33.      * The default initial capacity - MUST be a power of two. 
  34. * 默认初始化数组大小为16 
  35.      */  
  36.     static final int DEFAULT_INITIAL_CAPACITY = 1 << 4// aka 16  
  37.   
  38.     /** 
  39.      * The maximum capacity, used if a higher value is implicitly specified 
  40.      * by either of the constructors with arguments. 
  41.      * MUST be a power of two <= 1<<30. 
  42.      */  
  43.     static final int MAXIMUM_CAPACITY = 1 << 30;  
  44.   
  45.     /** 
  46.      * The load factor used when none specified in constructor. 
  47. * 默认装载因子, 
  48.      */  
  49.     static final float DEFAULT_LOAD_FACTOR = 0.75f;  
  50.   
  51.     /** 
  52.      * The bin count threshold for using a tree rather than list for a 
  53.      * bin.  Bins are converted to trees when adding an element to a 
  54.      * bin with at least this many nodes. The value must be greater 
  55.      * than 2 and should be at least 8 to mesh with assumptions in 
  56.      * tree removal about conversion back to plain bins upon 
  57.      * shrinkage. 
  58. * 这是链表的最大长度,当大于这个长度时,链表转化为红黑树 
  59.      */  
  60.     static final int TREEIFY_THRESHOLD = 8;  
  61.   
  62.     /** 
  63.      * The bin count threshold for untreeifying a (split) bin during a 
  64.      * resize operation. Should be less than TREEIFY_THRESHOLD, and at 
  65.      * most 6 to mesh with shrinkage detection under removal. 
  66.      */  
  67.     static final int UNTREEIFY_THRESHOLD = 6;  
  68.   
  69.     /** 
  70.      * The smallest table capacity for which bins may be treeified. 
  71.      * (Otherwise the table is resized if too many nodes in a bin.) 
  72.      * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts 
  73.      * between resizing and treeification thresholds. 
  74.      */  
  75.     static final int MIN_TREEIFY_CAPACITY = 64;  


 

三、构造函数

[java] view plain copy
  1. //可以自己指定初始容量和装载因子  
  2.     public HashMap(int initialCapacity, float loadFactor) {  
  3.         if (initialCapacity < 0)  
  4.             throw new IllegalArgumentException("Illegal initial capacity: " +  
  5.                                                initialCapacity);  
  6.         if (initialCapacity > MAXIMUM_CAPACITY)  
  7.             initialCapacity = MAXIMUM_CAPACITY;  
  8.         if (loadFactor <= 0 || Float.isNaN(loadFactor))  
  9.             throw new IllegalArgumentException("Illegal load factor: " +  
  10.                                                loadFactor);  
  11.         this.loadFactor = loadFactor;  
  12.         //重新定义了扩容的门限  
  13.         this.threshold = tableSizeFor(initialCapacity);  
  14. }  
  15.   
  16. /** 
  17.      * Returns a power of two size for the given target capacity. 
  18.      */  
  19.     static final int tableSizeFor(int cap) {  
  20.         int n = cap - 1;  
  21.         //先移位再或运算,最终保证返回值是2的整数幂  
  22.         n |= n >>> 1;  
  23.         n |= n >>> 2;  
  24.         n |= n >>> 4;  
  25.         n |= n >>> 8;  
  26.         n |= n >>> 16;  
  27.         return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;  
  28.     }  
  29.   
  30.     /** 
  31.      * Constructs an empty <tt>HashMap</tt> with the specified initial 
  32.      * capacity and the default load factor (0.75). 
  33.      * 
  34.      * @param  initialCapacity the initial capacity. 
  35.      * @throws IllegalArgumentException if the initial capacity is negative. 
  36.      */  
  37. //当知道所要构建的数据容量的大小时,最好直接指定大小,提高效率  
  38.     public HashMap(int initialCapacity) {  
  39.         this(initialCapacity, DEFAULT_LOAD_FACTOR);  
  40.     }  
  41.   
  42.     /** 
  43.      * Constructs an empty <tt>HashMap</tt> with the default initial capacity 
  44.      * (16) and the default load factor (0.75). 
  45.      */  
  46.     public HashMap() {  
  47.         this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted  
  48.     }  
  49.   
  50.     //将map直接放入hashmap中  
  51.     public HashMap(Map<? extends K, ? extends V> m) {  
  52.         this.loadFactor = DEFAULT_LOAD_FACTOR;  
  53.         putMapEntries(m, false);  
  54.     }  
  55.   
  56. final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {  
  57.         int s = m.size();  
  58.         if (s > 0) {  
  59.             if (table == null) { // pre-size  
  60.                 float ft = ((float)s / loadFactor) + 1.0F;  
  61.                 int t = ((ft < (float)MAXIMUM_CAPACITY) ?  
  62.                          (int)ft : MAXIMUM_CAPACITY);  
  63.                 if (t > threshold)  
  64.                     threshold = tableSizeFor(t);  
  65.             }  
  66.             else if (s > threshold)  
  67.                 resize();  
  68.             for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {  
  69.                 K key = e.getKey();  
  70.                 V value = e.getValue();  
  71.                 putVal(hash(key), key, value, false, evict);  
  72.             }  
  73.         }  
  74. }  
  75.   
  76.   
  77. /** 
  78.      * Basic hash bin node, used for most entries.  (See below for 
  79.      * TreeNode subclass, and in LinkedMyHashMap for its Entry subclass.) 
  80.      */  
  81.     在hashMap的结构图中,hash数组就是用Node型数组实现的,许多Node类通过next组成链表,key、value实际存储在Node内部类中。  
  82.     public static class Node<K,V> implements Map.Entry<K,V> {  
  83.         final int hash;  
  84.         final K key;  
  85.         V value;  
  86.         Node<K,V> next;  
  87.   
  88.         Node(int hash, K key, V value, Node<K,V> next) {  
  89.             this.hash = hash;  
  90.             this.key = key;  
  91.             this.value = value;  
  92.             this.next = next;  
  93.         }  
  94.   
  95.         public final K getKey()        { return key; }  
  96.         public final V getValue()      { return value; }  
  97.         public final String toString() { return key + "=" + value; }  
  98.   
  99.         public final int hashCode() {  
  100.             return Objects.hashCode(key) ^ Objects.hashCode(value);  
  101.         }  
  102.   
  103.         public final V setValue(V newValue) {  
  104.             V oldValue = value;  
  105.             value = newValue;  
  106.             return oldValue;  
  107.         }  
  108.   
  109.         public final boolean equals(Object o) {  
  110.             if (o == this)  
  111.                 return true;  
  112.             if (o instanceof Map.Entry) {  
  113.                 Map.Entry<?,?> e = (Map.Entry<?,?>)o;  
  114.                 if (Objects.equals(key, e.getKey()) &&  
  115.                     Objects.equals(value, e.getValue()))  
  116.                     return true;  
  117.             }  
  118.             return false;  
  119.         }  
  120.     }  



 

四、重要的方法分析

1.put方法

[java] view plain copy
  1. /** 
  2.      * Associates the specified value with the specified key in thismap. 
  3.      * If the map previously contained a mapping for the key, the old 
  4.      * value is replaced. 
  5.      * 
  6. */  
  7. public V put(K key, V value) {  
  8.         return putVal(hash(key), key, value, falsetrue);  
  9.     }  
  10. static final int hash(Object key) {  
  11.         int h;  
  12.         //key的值为null时,hash值返回0,对应的table数组中的位置是0  
  13.         return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);  
  14.     }  
  15.   
  16. /** 
  17.      * Implements Map.put and related methods 
  18.      * 
  19.      * @param hash hash for key 
  20.      * @param key the key 
  21.      * @param value the value to put 
  22.      * @param onlyIfAbsent if true, don't change existing value 
  23.      * @param evict if false, the table is in creation mode. 
  24.      * @return previous value, or null if none 
  25.  */  
  26. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,  
  27.                    boolean evict) {  
  28.         Node<K,V>[] tab; Node<K,V> p; int n, i;  
  29. //先将table赋给tab,判断table是否为null或大小为0,若为真,就调用resize()初始化  
  30.         if ((tab = table) == null || (n = tab.length) == 0)  
  31.             n = (tab = resize()).length;  
  32. //通过i = (n - 1) & hash得到table中的index值,若为null,则直接添加一个newNode  
  33.         if ((p = tab[i = (n - 1) & hash]) == null)  
  34.             tab[i] = newNode(hash, key, value, null);  
  35.         else {  
  36.         //执行到这里,说明发生碰撞,即tab[i]不为空,需要组成单链表或红黑树  
  37.             Node<K,V> e; K k;  
  38.             if (p.hash == hash &&  
  39.                 ((k = p.key) == key || (key != null && key.equals(k))))  
  40. //此时p指的是table[i]中存储的那个Node,如果待插入的节点中hash值和key值在p中已经存在,则将p赋给e  
  41.                 e = p;  
  42. //如果table数组中node类的hash、key的值与将要插入的Node的hash、key不吻合,就需要在这个node节点链表或者树节点中查找。  
  43.             else if (p instanceof TreeNode)  
  44.             //当p属于红黑树结构时,则按照红黑树方式插入  
  45.                 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);  
  46.             else {  
  47.     //到这里说明碰撞的节点以单链表形式存储,for循环用来使单链表依次向后查找  
  48.                 for (int binCount = 0; ; ++binCount) {  
  49.         //将p的下一个节点赋给e,如果为null,创建一个新节点赋给p的下一个节点  
  50.                     if ((e = p.next) == null) {  
  51.                         p.next = newNode(hash, key, value, null);  
  52.         //如果冲突节点达到8个,调用treeifyBin(tab, hash),这个treeifyBin首先回去判断当前hash表的长度,如果不足64的话,实际上就只进行resize,扩容table,如果已经达到64,那么才会将冲突项存储结构改为红黑树。  
  53.   
  54.                         if (binCount >= TREEIFY_THRESHOLD - 1// -1 for 1st  
  55.                             treeifyBin(tab, hash);  
  56.                         break;  
  57.                     }  
  58. //如果有相同的hash和key,则退出循环  
  59.                     if (e.hash == hash &&  
  60.                         ((k = e.key) == key || (key != null && key.equals(k))))  
  61.                         break;  
  62.                     p = e;//将p调整为下一个节点  
  63.                 }  
  64.             }  
  65. //若e不为null,表示已经存在与待插入节点hash、key相同的节点,hashmap后插入的key值对应的value会覆盖以前相同key值对应的value值,就是下面这块代码实现的  
  66.             if (e != null) { // existing mapping for key  
  67.                 V oldValue = e.value;  
  68.         //判断是否修改已插入节点的value  
  69.                 if (!onlyIfAbsent || oldValue == null)  
  70.                     e.value = value;  
  71.                 afterNodeAccess(e);  
  72.                 return oldValue;  
  73.             }  
  74.         }  
  75.         ++modCount;//插入新节点后,hashmap的结构调整次数+1  
  76.         if (++size > threshold)  
  77.             resize();//HashMap中节点数+1,如果大于threshold,那么要进行一次扩容  
  78.         afterNodeInsertion(evict);  
  79.         return null;  
  80.     }  
[java] view plain copy
  1.   
[java] view plain copy
  1. 2.扩容函数resize()分析  
[java] view plain copy
  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;//定义临时Node数组型变量,作为hash table  
  12.         //读取hash table的长度  
  13.         int oldCap = (oldTab == null) ? 0 : oldTab.length;  
  14.         int oldThr = threshold;//读取扩容门限  
  15.         int newCap, newThr = 0;//初始化新的table长度和门限值  
  16.         if (oldCap > 0) {  
  17.             //执行到这里,说明table已经初始化  
  18.             if (oldCap >= MAXIMUM_CAPACITY) {  
  19.                 threshold = Integer.MAX_VALUE;  
  20.                 return oldTab;  
  21.             }  
  22.             //二倍扩容,容量和门限值都加倍  
  23.             else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&  
  24.                      oldCap >= DEFAULT_INITIAL_CAPACITY)  
  25.                 newThr = oldThr << 1// double threshold  
  26.         }  
  27.         else if (oldThr > 0// initial capacity was placed in threshold  
  28.         //用构造器初始化了门限值,将门限值直接赋给新table容量  
  29.             newCap = oldThr;  
  30.         else {                
  31.  // zero initial threshold signifies using defaults  
  32. //老的table容量和门限值都为0,初始化新容量,新门限值,在调用hashmap()方式构造容器时,就采用这种方式初始化  
  33.             newCap = DEFAULT_INITIAL_CAPACITY;  
  34.             newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);  
  35.         }  
  36.         if (newThr == 0) {  
  37.             //如果门限值为0,重新设置门限  
  38.             float ft = (float)newCap * loadFactor;  
  39.             newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?  
  40.                       (int)ft : Integer.MAX_VALUE);  
  41.         }  
  42.         threshold = newThr;//更新新门限值为threshold  
  43.         @SuppressWarnings({"rawtypes","unchecked"})  
  44.        //初始化新的table数组  
  45.         Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];  
  46.         table = newTab;  
  47.         //当原来的table不为null时,需要将table[i]中的节点迁移  
  48.         if (oldTab != null) {  
  49.             for (int j = 0; j < oldCap; ++j) {  
  50.                 Node<K,V> e;  
  51.                 //取出链表中第一个节点保存,若不为null,继续下面操作  
  52.                 if ((e = oldTab[j]) != null) {  
  53.                     oldTab[j] = null;//主动释放  
  54.                     if (e.next == null)  
  55.     //链表中只有一个节点,没有后续节点,则直接重新计算在新table中的index,并将此节点存储到新table对应的index位置处  
  56.                         newTab[e.hash & (newCap - 1)] = e;  
  57.                     else if (e instanceof TreeNode)  
  58.                     //若e是红黑树节点,则按红黑树移动  
  59.                         ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);  
  60.                     else { // preserve order  
  61.                     //迁移单链表中的每个节点  
  62.                         Node<K,V> loHead = null, loTail = null;  
  63.                         Node<K,V> hiHead = null, hiTail = null;  
  64.                         Node<K,V> next;  
  65.                         do {  
  66. //下面这段暂时没有太明白,通过e.hash & oldCap将链表分为两队,参考知乎上的一段解释  
  67. /** 
  68. * 把链表上的键值对按hash值分成lo和hi两串,lo串的新索引位置与原先相同[原先位 
  69. * j],hi串的新索引位置为[原先位置j+oldCap]; 
  70. * 链表的键值对加入lo还是hi串取决于 判断条件if ((e.hash & oldCap) == 0),因为* capacity是2的幂,所以oldCap为10...0的二进制形式,若判断条件为真,意味着 
  71. * oldCap为1的那位对应的hash位为0,对新索引的计算没有影响(新索引 
  72. * =hash&(newCap-*1),newCap=oldCap<<2);若判断条件为假,则 oldCap为1的那位* 对应的hash位为1, 
  73. * 即新索引=hash&( newCap-1 )= hash&( (oldCap<<2) - 1),相当于多了10...0, 
  74. * 即 oldCap 
  75.  
  76. * 例子: 
  77. * 旧容量=16,二进制10000;新容量=32,二进制100000 
  78. * 旧索引的计算: 
  79. * hash = xxxx xxxx xxxy xxxx 
  80. * 旧容量-1 1111 
  81. * &运算 xxxx 
  82. * 新索引的计算: 
  83. * hash = xxxx xxxx xxxy xxxx 
  84. * 新容量-1 1 1111 
  85. * &运算 y xxxx 
  86. * 新索引 = 旧索引 + y0000,若判断条件为真,则y=0(lo串索引不变),否则y=1(hi串 
  87. * 索引=旧索引+旧容量10000) 
  88.    */  
  89.   
  90.                             next = e.next;  
  91.                             if ((e.hash & oldCap) == 0) {  
  92.                                 if (loTail == null)  
  93.                                     loHead = e;  
  94.                                 else  
  95.                                     loTail.next = e;  
  96.                                 loTail = e;  
  97.                             }  
  98.                             else {  
  99.                                 if (hiTail == null)  
  100.                                     hiHead = e;  
  101.                                 else  
  102.                                     hiTail.next = e;  
  103.                                 hiTail = e;  
  104.                             }  
  105.                         } while ((e = next) != null);  
  106.                         if (loTail != null) {  
  107.                             loTail.next = null;  
  108.                             newTab[j] = loHead;  
  109.                         }  
  110.                         if (hiTail != null) {  
  111.                             hiTail.next = null;  
  112.                             newTab[j + oldCap] = hiHead;  
  113.                         }  
  114.                     }  
  115.                 }  
  116.             }  
  117.         }  
  118.         return newTab;  
  119.     }  
[java] view plain copy
  1. 3.get方法  
[java] view plain copy
  1. /** 
  2.      * Returns the value to which the specified key is mapped, 
  3.      * or {@code null} if this map contains no mapping for the key. 
  4.      * 
  5.      * <p>More formally, if this map contains a mapping from a key 
  6.      * {@code k} to a value {@code v} such that {@code (key==null ? k==null : 
  7.      * key.equals(k))}, then this method returns {@code v}; otherwise 
  8.      * it returns {@code null}.  (There can be at most one such mapping.) 
  9.      * 
  10.      * <p>A return value of {@code null} does not <i>necessarily</i> 
  11.      * indicate that the map contains no mapping for the key; it's also 
  12.      * possible that the map explicitly maps the key to {@code null}. 
  13.      * The {@link #containsKey containsKey} operation may be used to 
  14.      * distinguish these two cases. 
  15.      * 
  16.      * @see #put(Object, Object) 
  17.      */  
  18.     public V get(Object key) {  
  19.         Node<K,V> e;  
  20.         return (e = getNode(hash(key), key)) == null ? null : e.value;  
  21.     }  
  22.   
  23.     /** 
  24.      * Implements Map.get and related methods 
  25.      * 
  26.      * @param hash hash for key 
  27.      * @param key the key 
  28.      * @return the node, or null if none 
  29.      */  
  30.     final Node<K,V> getNode(int hash, Object key) {  
  31.         Node<K,V>[] tab; Node<K,V> first, e; int n; K k;  
  32.         if ((tab = table) != null && (n = tab.length) > 0 &&  
  33.             (first = tab[(n - 1) & hash]) != null) {  
  34.             if (first.hash == hash && // always check first node  
  35.                 ((k = first.key) == key || (key != null && key.equals(k))))  
  36.                 return first;  
  37.             if ((e = first.next) != null) {  
  38.            //分为红黑树和链表查找两种  
  39.                 if (first instanceof TreeNode)  
  40.                     return ((TreeNode<K,V>)first).getTreeNode(hash, key);  
  41.                 do {  
  42.                     if (e.hash == hash &&  
  43.                         ((k = e.key) == key || (key != null && key.equals(k))))  
  44.                         return e;  
  45.                 } while ((e = e.next) != null);  
  46.             }  
  47.         }  
  48.         return null;  
  49.     }  
  50.   
  51.   
  52.   
  53. /** 
  54.      * Returns <tt>true</tt> if this map contains a mapping for the 
  55.      * specified key. 
  56.      * 
  57.      * @param   key   The key whose presence in this map is to be tested 
  58.      * @return <tt>true</tt> if this map contains a mapping for the specified 
  59.      * key. 
  60.      */  
  61.     public boolean containsKey(Object key) {  
  62.         return getNode(hash(key), key) != null;  
  63.     }  
[java] view plain copy
  1. 4.红黑树  
[java] view plain copy
  1. /** 
  2.      * Entry for Tree bins. Extends LinkedMyHashMap.Entry (which in turn 
  3.      * extends Node) so can be used as extension of either regular or 
  4.      * linked node. 
  5.      */  
  6.     static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {  
  7.         TreeNode<K,V> parent;  // red-black tree links  
  8.         TreeNode<K,V> left;  
  9.         TreeNode<K,V> right;  
  10.         TreeNode<K,V> prev;    // needed to unlink next upon deletion  
  11.         boolean red;  
  12.         TreeNode(int hash, K key, V val, Node<K,V> next) {  
  13.             super(hash, key, val, next);  
  14.         }  
  15.   
  16.         //红黑树暂时还没有仔细研究,红黑树相关的增删改查操作后期再认真分析。  



五、总结

仔细分析hashmap源码后,可以掌握很多常用的数据结构的用法。本次笔记只是记录了hashmap几个常用的方法,像红黑树、迭代器等还没有仔细研究,后面有时间会认真分析。

网友文章参考http://www.cnblogs.com/ToBeAProgrammer/p/4787761.html

http://wenku.baidu.com/link?url=AHcaJRmJofOxRbX6L8vKoYSW59Tl-GJexJjNUdEvHuAwDgRtPfCzHhVTO21v7BV0V-OTp7D0BC3sh2jdctV9RYnwhM_6w8SlZ9Np-cago-7

0 0