HashMap 简介 HashMap 主要用来存放键值对,它基于哈希表的 Map 接口实现,是常用的 Java 集合之一,是非线程安全的。
HashMap 可以存储 null 的 key 和 value,但 null 作为键只能有一个,null 作为值可以有多个
JDK1.8 之前 HashMap 由 数组+链表 组成的,数组是 HashMap 的主体,链表则是主要为了解决哈希冲突而存在的(“拉链法”解决冲突)。 JDK1.8 以后的 HashMap 在解决哈希冲突时有了较大的变化,当链表长度大于阈值(默认为 8)(将链表转换成红黑树前会判断,如果当前数组的长度小于 64,那么会选择先进行数组扩容,而不是转换为红黑树)时,将链表转化为红黑树,以减少搜索时间。
HashMap 默认的初始化大小为 16。之后每次扩充,容量变为原来的 2 倍。并且, HashMap 总是使用 2 的幂作为哈希表的大小。
底层数据结构分析 DK1.8 之前 JDK1.8 之前 HashMap 底层是 数组和链表  结合在一起使用也就是 链表散列 。
HashMap 通过 key 的 hashCode 经过扰动函数处理过后得到 hash 值,然后通过 (n - 1) & hash 判断当前元素存放的位置(这里的 n 指的是数组的长度),如果当前位置存在元素的话,就判断该元素与要存入的元素的 hash 值以及 key 是否相同,如果相同的话,直接覆盖,不相同就通过拉链法解决冲突。
所谓扰动函数指的就是 HashMap 的 hash 方法。使用 hash 方法也就是扰动函数是为了防止一些实现比较差的 hashCode() 方法 换句话说使用扰动函数之后可以减少碰撞。
JDK 1.8 HashMap 的 hash 方法源码: 
JDK 1.8 的 hash 方法 相比于 JDK 1.7 hash 方法更加简化,但是原理不变。
1 2 3 4 5 6 7   static  final  int  hash (Object key)   {     int  h;                    return  (key == null ) ? 0  : (h = key.hashCode()) ^ (h >>> 16 ); } 
 
对比一下 JDK1.7 的 HashMap 的 hash 方法源码.
1 2 3 4 5 6 7 8 static  int  hash (int  h)   {                   h ^= (h >>> 20 ) ^ (h >>> 12 );     return  h ^ (h >>> 7 ) ^ (h >>> 4 ); } 
 
相比于 JDK1.8 的 hash 方法 ,JDK 1.7 的 hash 方法的性能会稍差一点点,因为毕竟扰动了 4 次。
所谓 “拉链法”  就是:将链表和数组相结合。也就是说创建一个链表数组,数组中每一格就是一个链表。若遇到哈希冲突,则将冲突的值加到链表中即可。
JDK1.8 之后 相比于之前的版本,JDK1.8 以后在解决哈希冲突时有了较大的变化。
当链表长度大于阈值(默认为 8)时,会首先调用 treeifyBin()方法。这个方法会根据 HashMap 数组来决定是否转换为红黑树。只有当数组长度大于或者等于 64 的情况下,才会执行转换红黑树操作,以减少搜索时间。否则,就是只是执行 resize() 方法对数组扩容。相关源码这里就不贴了,重点关注 treeifyBin()方法即可!
类的属性: 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 public  class  HashMap <K ,V > extends  AbstractMap <K ,V > implements  Map <K ,V >, Cloneable , Serializable   {         private  static  final  long  serialVersionUID = 362498820763181265L ;          static  final  int  DEFAULT_INITIAL_CAPACITY = 1  << 4 ;          static  final  int  MAXIMUM_CAPACITY = 1  << 30 ;          static  final  float  DEFAULT_LOAD_FACTOR = 0.75f ;          static  final  int  TREEIFY_THRESHOLD = 8 ;          static  final  int  UNTREEIFY_THRESHOLD = 6 ;          static  final  int  MIN_TREEIFY_CAPACITY = 64 ;          transient  Node<k,v>[] table;          transient  Set<map.entry<k,v>> entrySet;          transient  int  size;          transient  int  modCount;          int  threshold;          final  float  loadFactor; } 
 
loadFactor 加载因子 
loadFactor 加载因子是控制数组存放数据的疏密程度,loadFactor 越趋近于 1,那么 数组中存放的数据(entry)也就越多,也就越密,也就是会让链表的长度增加,loadFactor 越小,也就是趋近于 0,数组中存放的数据(entry)也就越少,也就越稀疏。
loadFactor 太大导致查找元素效率低,太小导致数组的利用率低,存放的数据会很分散。loadFactor 的默认值为 0.75f 是官方给出的一个比较好的临界值 。
给定的默认容量为 16,负载因子为 0.75。Map 在使用过程中不断的往里面存放数据,当数量达到了 16 * 0.75 = 12 就需要将当前 16 的容量进行扩容,而扩容这个过程涉及到 rehash、复制数据等操作,所以非常消耗性能。
 
threshold 
threshold = capacity * loadFactor ,当 Size>=threshold 的时候,那么就要考虑对数组的扩增了,也就是说,这个的意思就是 衡量数组是否需要扩增的一个标准 。
 
 
Node 节点类源码: 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 static  class  Node <K ,V > implements  Map .Entry <K ,V >  {       final  int  hash;        final  K key;        V value;                Node<K,V> next;        Node(int  hash, K key, V value, Node<K,V> next) {             this .hash = hash;             this .key = key;             this .value = value;             this .next = next;         }         public  final  K getKey ()          { return  key; }         public  final  V getValue ()        { return  value; }         public  final  String toString ()   { return  key + "="  + value; }                  public  final  int  hashCode ()   {             return  Objects.hashCode(key) ^ Objects.hashCode(value);         }         public  final  V setValue (V newValue)   {             V oldValue = value;             value = newValue;             return  oldValue;         }                  public  final  boolean  equals (Object o)   {             if  (o == this )                 return  true ;             if  (o instanceof  Map.Entry) {                 Map.Entry<?,?> e = (Map.Entry<?,?>)o;                 if  (Objects.equals(key, e.getKey()) &&                     Objects.equals(value, e.getValue()))                     return  true ;             }             return  false ;         } } 
 
树节点类源码: 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 static  final  class  TreeNode <K ,V > extends  LinkedHashMap .Entry <K ,V >  {        TreeNode<K,V> parent;           TreeNode<K,V> left;             TreeNode<K,V> right;            TreeNode<K,V> prev;             boolean  red;                    TreeNode(int  hash, K key, V val, Node<K,V> next) {             super (hash, key, val, next);         }                  final  TreeNode<K,V> root ()   {             for  (TreeNode<K,V> r = this , p;;) {                 if  ((p = r.parent) == null )                     return  r;                 r = p;        } 
 
HashMap 源码分析 构造方法 HashMap 中有四个构造方法,它们分别如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 public  HashMap ()   {    this .loadFactor = DEFAULT_LOAD_FACTOR;   }    public  HashMap (Map<? extends K, ? extends V> m)   {      this .loadFactor = DEFAULT_LOAD_FACTOR;      putMapEntries(m, false );  }    public  HashMap (int  initialCapacity)   {      this (initialCapacity, DEFAULT_LOAD_FACTOR);  }    public  HashMap (int  initialCapacity, float  loadFactor)   {      if  (initialCapacity < 0 )          throw  new  IllegalArgumentException("Illegal initial capacity: "  + initialCapacity);      if  (initialCapacity > MAXIMUM_CAPACITY)          initialCapacity = MAXIMUM_CAPACITY;      if  (loadFactor <= 0  || Float.isNaN(loadFactor))          throw  new  IllegalArgumentException("Illegal load factor: "  + loadFactor);      this .loadFactor = loadFactor;      this .threshold = tableSizeFor(initialCapacity);  } 
 
putMapEntries 方法: 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 final  void  putMapEntries (Map<? extends K, ? extends V> m, boolean  evict)   {    int  s = m.size();     if  (s > 0 ) {                  if  (table == null ) {                           float  ft = ((float )s / loadFactor) + 1.0F ;             int  t = ((ft < (float )MAXIMUM_CAPACITY) ?                     (int )ft : MAXIMUM_CAPACITY);                          if  (t > threshold)                 threshold = tableSizeFor(t);         }                  else  if  (s > threshold)             resize();                  for  (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {             K key = e.getKey();             V value = e.getValue();             putVal(hash(key), key, value, false , evict);         }     } } 
 
put 方法 HashMap 只提供了 put 用于添加元素,putVal 方法只是给 put 方法调用的一个方法,并没有提供给用户使用。
对 putVal 方法添加元素的分析如下: 
如果定位到的数组位置没有元素 就直接插入。 
如果定位到的数组位置有元素就和要插入的 key 比较,如果 key 相同就直接覆盖,如果 key 不相同,就判断 p 是否是一个树节点,如果是就调用e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value)将元素添加进入。如果不是就遍历链表插入(插入的是链表尾部)。 
 
说明:上图有两个小问题:
直接覆盖之后应该就会 return,不会有后续操作。参考 JDK8 HashMap.java 658 行(issue#608  
 
  
 (opens new window) )。
当链表长度大于阈值(默认为 8)并且 HashMap 数组长度超过 64 的时候才会执行链表转红黑树的操作,否则就只是对数组扩容。参考 HashMap 的 treeifyBin() 方法(issue#1087 
   (opens new window) )。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 public  V put (K key, V value)   {    return  putVal(hash(key), key, value, false , true ); } final  V putVal (int  hash, K key, V value, boolean  onlyIfAbsent,                    boolean  evict)   {    Node<K,V>[] tab; Node<K,V> p; int  n, i;          if  ((tab = table) == null  || (n = tab.length) == 0 )         n = (tab = resize()).length;          if  ((p = tab[i = (n - 1 ) & hash]) == null )         tab[i] = newNode(hash, key, value, null );          else  {         Node<K,V> e; K k;                  if  (p.hash == hash &&             ((k = p.key) == key || (key != null  && key.equals(k))))                                  e = p;                  else  if  (p instanceof  TreeNode)                          e = ((TreeNode<K,V>)p).putTreeVal(this , tab, hash, key, value);                  else  {                          for  (int  binCount = 0 ; ; ++binCount) {                                  if  ((e = p.next) == null ) {                                          p.next = newNode(hash, key, value, null );                                                                                    if  (binCount >= TREEIFY_THRESHOLD - 1 )                          treeifyBin(tab, hash);                                          break ;                 }                                  if  (e.hash == hash &&                     ((k = e.key) == key || (key != null  && key.equals(k))))                                          break ;                                  p = e;             }         }                  if  (e != null ) {                          V oldValue = e.value;                          if  (!onlyIfAbsent || oldValue == null )                                  e.value = value;                          afterNodeAccess(e);                          return  oldValue;         }     }          ++modCount;          if  (++size > threshold)         resize();          afterNodeInsertion(evict);     return  null ; } 
 
我们再来对比一下 JDK1.7 put 方法的代码 
对于 put 方法的分析如下: 
① 如果定位到的数组位置没有元素 就直接插入。 
② 如果定位到的数组位置有元素,遍历以这个元素为头结点的链表,依次和插入的 key 比较,如果 key 相同就直接覆盖,不同就采用头插法插入元素。 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public  V put (K key, V value)     if  (table == EMPTY_TABLE)   {    inflateTable(threshold); }     if  (key == null )         return  putForNullKey(value);     int  hash = hash(key);     int  i = indexFor(hash, table.length);     for  (Entry<K,V> e = table[i]; e != null ; e = e.next) {          Object k;         if  (e.hash == hash && ((k = e.key) == key || key.equals(k))) {             V oldValue = e.value;             e.value = value;             e.recordAccess(this );             return  oldValue;         }     }     modCount++;     addEntry(hash, key, value, i);       return  null ; } 
 
get 方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 public  V get (Object key)   {    Node<K,V> e;     return  (e = getNode(hash(key), key)) == null  ? null  : e.value; } 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 &&              ((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 ; } 
 
resize 方法 进行扩容,会伴随着一次重新 hash 分配,并且会遍历 hash 表中所有的元素,是非常耗时的。在编写程序中,要尽量避免 resize。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 final  Node<K,V>[] resize() {    Node<K,V>[] oldTab = table;     int  oldCap = (oldTab == null ) ? 0  : oldTab.length;     int  oldThr = threshold;     int  newCap, newThr = 0 ;     if  (oldCap > 0 ) {                  if  (oldCap >= MAXIMUM_CAPACITY) {             threshold = Integer.MAX_VALUE;             return  oldTab;         }                  else  if  ((newCap = oldCap << 1 ) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)             newThr = oldThr << 1 ;      }     else  if  (oldThr > 0 )          newCap = oldThr;     else  {                  newCap = DEFAULT_INITIAL_CAPACITY;         newThr = (int )(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);     }          if  (newThr == 0 ) {         float  ft = (float )newCap * loadFactor;         newThr = (newCap < MAXIMUM_CAPACITY && ft < (float )MAXIMUM_CAPACITY ? (int )ft : Integer.MAX_VALUE);     }     threshold = newThr;     @SuppressWarnings({"rawtypes","unchecked"})          Node<K,V>[] newTab = (Node<K,V>[])new  Node[newCap];     table = newTab;     if  (oldTab != null ) {                  for  (int  j = 0 ; j < oldCap; ++j) {             Node<K,V> e;             if  ((e = oldTab[j]) != null ) {                 oldTab[j] = null ;                 if  (e.next == null )                     newTab[e.hash & (newCap - 1 )] = e;                 else  if  (e instanceof  TreeNode)                     ((TreeNode<K,V>)e).split(this , newTab, j, oldCap);                 else  {                     Node<K,V> loHead = null , loTail = null ;                     Node<K,V> hiHead = null , hiTail = null ;                     Node<K,V> next;                     do  {                         next = e.next;                                                  if  ((e.hash & oldCap) == 0 ) {                             if  (loTail == null )                                 loHead = e;                             else                                  loTail.next = e;                             loTail = e;                         }                                                  else  {                             if  (hiTail == null )                                 hiHead = e;                             else                                  hiTail.next = e;                             hiTail = e;                         }                     } while  ((e = next) != null );                                          if  (loTail != null ) {                         loTail.next = null ;                         newTab[j] = loHead;                     }                                          if  (hiTail != null ) {                         hiTail.next = null ;                         newTab[j + oldCap] = hiHead;                     }                 }             }         }     }     return  newTab; } 
 
HashMap 常用方法测试 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 package  map;import  java.util.Collection;import  java.util.HashMap;import  java.util.Set;public  class  HashMapDemo   {    public  static  void  main (String[] args)   {         HashMap<String, String> map = new  HashMap<String, String>();                  map.put("san" , "张三" );         map.put("si" , "李四" );         map.put("wu" , "王五" );         map.put("wang" , "老王" );         map.put("wang" , "老王2" );         map.put("lao" , "老王" );         System.out.println("-------直接输出hashmap:-------" );         System.out.println(map);                           System.out.println("-------foreach获取Map中所有的键:------" );         Set<String> keys = map.keySet();         for  (String key : keys) {             System.out.print(key+"  " );         }         System.out.println();                  System.out.println("-------foreach获取Map中所有的值:------" );         Collection<String> values = map.values();         for  (String value : values) {             System.out.print(value+"  " );         }         System.out.println();                  System.out.println("-------得到key的值的同时得到key所对应的值:-------" );         Set<String> keys2 = map.keySet();         for  (String key : keys2) {             System.out.print(key + ":"  + map.get(key)+"   " );         }                                                      Set<java.util.Map.Entry<String, String>> entrys = map.entrySet();         for  (java.util.Map.Entry<String, String> entry : entrys) {             System.out.println(entry.getKey() + "--"  + entry.getValue());         }                  System.out.println("after map.size():" +map.size());         System.out.println("after map.isEmpty():" +map.isEmpty());         System.out.println(map.remove("san" ));         System.out.println("after map.remove():" +map);         System.out.println("after map.get(si):" +map.get("si" ));         System.out.println("after map.containsKey(si):" +map.containsKey("si" ));         System.out.println("after containsValue(李四):" +map.containsValue("李四" ));         System.out.println(map.replace("si" , "李四2" ));         System.out.println("after map.replace(si, 李四2):" +map);     } }