HashMap源碼分析

 

HashMap 簡介

HashMap 主要用來存放鍵值對,它基於哈希表的Map接口實現,是經常使用的Java集合之一。java

JDK1.8 以前 HashMap 由 數組+鏈表 組成的,數組是 HashMap 的主體,鏈表則是主要爲了解決哈希衝突而存在的(「拉鍊法」解決衝突).JDK1.8 之後在解決哈希衝突時有了較大的變化,當鏈表長度大於閾值(默認爲 8)時,將鏈表轉化爲紅黑樹(將鏈表轉換成紅黑樹前會判斷,若是當前數組的長度小於 64,那麼會選擇先進行數組擴容,而不是轉換爲紅黑樹),以減小搜索時間,具體能夠參考 treeifyBin方法。node

底層數據結構分析

JDK1.8以前

JDK1.8 以前 HashMap 底層是 數組和鏈表 結合在一塊兒使用也就是 鏈表散列。HashMap 經過 key 的 hashCode 通過擾動函數處理事後獲得 hash 值,而後經過 (n - 1) & hash 判斷當前元素存放的位置(這裏的 n 指的是數組的長度),若是當前位置存在元素的話,就判斷該元素與要存入的元素的 hash 值以及 key 是否相同,若是相同的話,直接覆蓋,不相同就經過拉鍊法解決衝突。git

所謂擾動函數指的就是 HashMap 的 hash 方法。使用 hash 方法也就是擾動函數是爲了防止一些實現比較差的 hashCode() 方法 換句話說使用擾動函數以後能夠減小碰撞。數組

JDK 1.8 HashMap 的 hash 方法源碼:數據結構

JDK 1.8 的 hash方法 相比於 JDK 1.7 hash 方法更加簡化,可是原理不變。app

    static final int hash(Object key) {  int h;  // key.hashCode():返回散列值也就是hashcode  // ^ :按位異或  // >>>:無符號右移,忽略符號位,空位都以0補齊  return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);  }

對比一下 JDK1.7的 HashMap 的 hash 方法源碼.ide

static int hash(int h) {  // This function ensures that hashCodes that differ only by  // constant multiples at each bit position have a bounded  // number of collisions (approximately 8 at default load factor).   h ^= (h >>> 20) ^ (h >>> 12);  return h ^ (h >>> 7) ^ (h >>> 4); }

相比於 JDK1.8 的 hash 方法 ,JDK 1.7 的 hash 方法的性能會稍差一點點,由於畢竟擾動了 4 次。函數

所謂 「拉鍊法」 就是:將鏈表和數組相結合。也就是說建立一個鏈表數組,數組中每一格就是一個鏈表。若遇到哈希衝突,則將衝突的值加到鏈表中便可。源碼分析

jdk1.8以前的內部結構

JDK1.8以後

相比於以前的版本,jdk1.8在解決哈希衝突時有了較大的變化,當鏈表長度大於閾值(默認爲8)時,將鏈表轉化爲紅黑樹,以減小搜索時間。性能

JDK1.8以後的HashMap底層數據結構

類的屬性:

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {  // 序列號  private static final long serialVersionUID = 362498820763181265L;  // 默認的初始容量是16  static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;  // 最大容量  static final int MAXIMUM_CAPACITY = 1 << 30;  // 默認的填充因子  static final float DEFAULT_LOAD_FACTOR = 0.75f;  // 當桶(bucket)上的結點數大於這個值時會轉成紅黑樹  static final int TREEIFY_THRESHOLD = 8;  // 當桶(bucket)上的結點數小於這個值時樹轉鏈表  static final int UNTREEIFY_THRESHOLD = 6;  // 桶中結構轉化爲紅黑樹對應的table的最小大小  static final int MIN_TREEIFY_CAPACITY = 64;  // 存儲元素的數組,老是2的冪次倍  transient Node<k,v>[] table;  // 存放具體元素的集  transient Set<map.entry<k,v>> entrySet;  // 存放元素的個數,注意這個不等於數組的長度。  transient int size;  // 每次擴容和更改map結構的計數器  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節點類源碼:

// 繼承自 Map.Entry<K,V> static class Node<K,V> implements Map.Entry<K,V> {  final int hash;// 哈希值,存放元素到hashmap中時用來與其餘元素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; }  // 重寫hashCode()方法  public final int hashCode() {  return Objects.hashCode(key) ^ Objects.hashCode(value);  }   public final V setValue(V newValue) {  V oldValue = value;  value = newValue;  return oldValue;  }  // 重寫 equals() 方法  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;  } }

樹節點類源碼:

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; // needed to unlink next upon deletion  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 中有四個構造方法,它們分別以下:

    // 默認構造函數。  public HashMap() {  this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted  }   // 包含另外一個「Map」的構造函數  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方法:

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {  int s = m.size();  if (s > 0) {  // 判斷table是否已經初始化  if (table == null) { // pre-size  // 未初始化,s爲m的實際元素個數  float ft = ((float)s / loadFactor) + 1.0F;  int t = ((ft < (float)MAXIMUM_CAPACITY) ?  (int)ft : MAXIMUM_CAPACITY);  // 計算獲得的t大於閾值,則初始化閾值  if (t > threshold)  threshold = tableSizeFor(t);  }  // 已初始化,而且m元素個數大於閾值,進行擴容處理  else if (s > threshold)  resize();  // 將m中的全部元素添加至HashMap中  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)將元素添加進入。若是不是就遍歷鏈表插入(插入的是鏈表尾部)。

put方法

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;  // table未初始化或者長度爲0,進行擴容  if ((tab = table) == null || (n = tab.length) == 0)  n = (tab = resize()).length;  // (n - 1) & hash 肯定元素存放在哪一個桶中,桶爲空,新生成結點放入桶中(此時,這個結點是放在數組中)  if ((p = tab[i = (n - 1) & hash]) == null)  tab[i] = newNode(hash, key, value, null);  // 桶中已經存在元素  else {  Node<K,V> e; K k;  // 比較桶中第一個元素(數組中的結點)的hash值相等,key相等  if (p.hash == hash &&  ((k = p.key) == key || (key != null && key.equals(k))))  // 將第一個元素賦值給e,用e來記錄  e = p;  // hash值不相等,即key不相等;爲紅黑樹結點  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) // -1 for 1st  treeifyBin(tab, hash);  // 跳出循環  break;  }  // 判斷鏈表中結點的key值與插入的元素的key值是否相等  if (e.hash == hash &&  ((k = e.key) == key || (key != null && key.equals(k))))  // 相等,跳出循環  break;  // 用於遍歷桶中的鏈表,與前面的e = p.next組合,能夠遍歷鏈表  p = e;  }  }  // 表示在桶中找到key值、hash值與插入元素相等的結點  if (e != null) {  // 記錄e的value  V oldValue = e.value;  // onlyIfAbsent爲false或者舊值爲null  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相同就直接覆蓋,不一樣就採用頭插法插入元素。
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方法

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 && // always check first node  ((k = first.key) == key || (key != null && key.equals(k))))  return first;  // 桶中不止一個節點  if ((e = first.next) != null) {  // 在樹中get  if (first instanceof TreeNode)  return ((TreeNode<K,V>)first).getTreeNode(hash, key);  // 在鏈表中get  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。

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;  }  // 沒超過最大值,就擴充爲原來的2倍  else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)  newThr = oldThr << 1; // double threshold  }  else if (oldThr > 0) // initial capacity was placed in threshold  newCap = oldThr;  else {  // signifies using defaults  newCap = DEFAULT_INITIAL_CAPACITY;  newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);  }  // 計算新的resize上限  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) {  // 把每一個bucket都移動到新的buckets中  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;  }  // 原索引+oldCap  else {  if (hiTail == null)  hiHead = e;  else  hiTail.next = e;  hiTail = e;  }  } while ((e = next) != null);  // 原索引放到bucket裏  if (loTail != null) {  loTail.next = null;  newTab[j] = loHead;  }  // 原索引+oldCap放到bucket裏  if (hiTail != null) {  hiTail.next = null;  newTab[j + oldCap] = hiHead;  }  }  }  }  }  return newTab; }

HashMap經常使用方法測試

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);  /**  * 遍歷HashMap  */  // 1.獲取Map中的全部鍵  System.out.println("-------foreach獲取Map中全部的鍵:------");  Set<String> keys = map.keySet();  for (String key : keys) {  System.out.print(key+" ");  }  System.out.println();//換行  // 2.獲取Map中全部值  System.out.println("-------foreach獲取Map中全部的值:------");  Collection<String> values = map.values();  for (String value : values) {  System.out.print(value+" ");  }  System.out.println();//換行  // 3.獲得key的值的同時獲得key所對應的值  System.out.println("-------獲得key的值的同時獲得key所對應的值:-------");  Set<String> keys2 = map.keySet();  for (String key : keys2) {  System.out.print(key + ":" + map.get(key)+" ");   }  /**  * 另一種不經常使用的遍歷方式  */  // 當我調用put(key,value)方法的時候,首先會把key和value封裝到  // Entry這個靜態內部類對象中,把Entry對象再添加到數組中,因此咱們想獲取  // map中的全部鍵值對,咱們只要獲取數組中的全部Entry對象,接下來  // 調用Entry對象中的getKey()和getValue()方法就能獲取鍵值對了  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());  }   /**  * HashMap其餘經常使用方法  */  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);  }  }
相關文章
相關標籤/搜索