有大半年沒有寫博客了,雖然一直有在看書學習,但如今回過來看讀書基本都是一種知識「輸入」,不少時候是水過無痕。而知識的「輸出」會逼着本身去找出沒有掌握或者瞭解不深入的東西,你要把一個知識點表達出來,本身沒有吃透是很難寫出來的。我算是明白了爲何有些人能夠經過寫博客來學習,我也不能懶了,堅持寫下去。html
都覺得本身對java的集合框架掌握得還能夠,打開源碼才發現我只是掌握了他們的基本使用,而對原理和數據結構方面只是略知一二。接下來的一段時間裏,我會寫一個專題詳細總結java集合框架知識,首先從HashMap開始吧。java
HashMap是以Key-Value方式存儲數據,Key用散列函數映射到table數組(散列表),解決衝突的方法是分離連接法。即HashMap的數據結構是:數組+鏈表+紅黑樹(java8增長了紅黑樹),其結構圖以下:node
HashMap繼承抽象類AbstractMap,實現了Map接口。抽象類AbstractMap實現了接口Map的部分方法,這樣子類就能夠經過繼承而共用這些方法,而無須再次實現了。數組
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable{}
從上面的分析,咱們知道HashMap的基本存儲單元是Node<K,V>,它保存一個Key-Value。每一個Node經過哈希函數映射到哈希桶數組,在源碼中用Node<K,V>[] table表示哈希桶數組。下面來看看Node的源碼(本文源碼都是基於java8):數據結構
static class Node<K,V> implements Map.Entry<K,V> { final int hash; //用來定位數組索引位置 final K key; V value; Node<K,V> next; //鏈表的下一個node Node(int hash, K key, V value, Node<K,V> next) { ... } public final K getKey(){ ... } public final V getValue() { ... } public final String toString() { ... } public final int hashCode() { ... } public final V setValue(V newValue) { ... } public final boolean equals(Object o) { ... } }
構造函數須要對下面幾個參數初始化(部分使用默認的)多線程
Node<K,V>[] table; // 哈希桶數組 int threshold;// 所能容納的key-value對極限,大於這個閥值將會進行擴容 final float loadFactor; // 負載因子 int modCount; // 記錄修改的次數 int size; // key-value對的個數
1.無參構造器app
負載因子決定哈希桶數組的疏密程度,太疏會形成空間浪費,太密容易造成哈希衝突,通常使用默認的。框架
public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // 初始化默認負載因子爲0.75 }
2.指定哈希桶數組初始容量構造器函數
public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR);// 調用兩個參數的構造器 }
3.指定哈希桶數組初始容量和負載因子構造器性能
public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; // 小於0或者不是數字時拋出異常 if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; this.threshold = tableSizeFor(initialCapacity);//確保閥值爲大於給定初始容量的最小2的n次冪,好比給定初始容量爲9,則閥值爲16(2的4次冪),給定爲25,則爲32(2的5次冪) }
1.put方法
public V put(K key, V value) { // 對key的hashCode()作hash 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; // tab爲空則建立 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 經過hash計算數組index,若是index位置沒有元素則直接插入Node對象 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); // index對應位置已經有元素了,說明hash碰撞了,則須要構建鏈表或者紅黑樹 else { Node<K,V> e; K k; // hash和key都相等,能夠當成是同一個對象,這時要麼覆蓋原來的value,要麼繼續使用原來的value if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; // index位置已經有紅黑樹了,加入新的節點 else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); // 在index位置構建鏈表 else { // 遍歷鏈表,把新的節點加入到表尾部 for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); // 當鏈表長度大於等於8時,轉換成紅黑樹 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } // 鏈表中有相同的hash和key,退出遍歷 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } // 鏈表或者紅黑樹中存在相同的key,判斷要不要覆蓋 if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; // 該函數提供給LinkedHashMap使用,維護了一個訪問鏈表 afterNodeAccess(e); return oldValue; } } // 修改數加1,爲多線程遍歷提供fast-fail機制 ++modCount; // 判斷是否須要擴容 if (++size > threshold) resize(); // java8中該方法基本空操做 afterNodeInsertion(evict); return null; }
2.get方法
get操做其實就是經過哈希值算出節點所在table數組的位置,而後判斷是鏈表仍是紅黑樹或者是恰好是要找的值
public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } // 這純粹是一個數學方法,>>>表示符號向右移動,假若有符號位-8表示爲11000,則-8 >>> 2 == 5,把符號位也當成了數值 static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; // 經過hash值計算index位置 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) { // 紅黑樹中查找 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; }
遍歷操做在內部抽象類HashIterator中實現,其實也是經過迭代器完成的,使用fast-fail機制保證遍歷時map不會改變。遍歷的迭代器會繼承HashIterator。
public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es; return (es = entrySet) == null ? (entrySet = new EntrySet()) : es; } abstract class HashIterator { Node<K,V> next; // next entry to return Node<K,V> current; // current entry int expectedModCount; // for fast-fail int index; // current slot // 初始化參數 HashIterator() { expectedModCount = modCount; Node<K,V>[] t = table; current = next = null; index = 0; // index從第一個不爲null的地方開始 if (t != null && size > 0) { // advance to first entry do {} while (index < t.length && (next = t[index++]) == null); } } public final boolean hasNext() { return next != null; } // 這個方法會被迭代器next()方法調用 final Node<K,V> nextNode() { Node<K,V>[] t; Node<K,V> e = next; // fast-fail判斷,避免遍歷的時候map有發生改變 if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (e == null) throw new NoSuchElementException(); // 判讀當前index位置是否還有下一個節點,就把下一個節點放到next,不然遍歷table數組 if ((next = (current = e).next) == null && (t = table) != null) { do {} while (index < t.length && (next = t[index++]) == null); } return e; } }
java8對HashMap的擴容作了優化,不用從新計算每一個node在table數組的位置,原有的node要麼在原來的index位置,要麼在index+擴容前容量對應的位置
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) { // 當容量大於(1 << 30== 1073741824),讓閾值等於最大整數,再也不擴容,就讓它碰撞吧 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } // 閾值擴大爲原來的兩倍 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 { // zero initial threshold signifies using defaults 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) { // 遍歷舊table數組的元素到新的table數組 for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null; // 在j處只有一個節點 if (e.next == null) newTab[e.hash & (newCap - 1)] = e; // 在j處是紅黑樹 else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next; // 這裏用了比較巧妙的方法,若是元素的hash值跟舊table數組的容量作按位與操做等於0, // 則在新table數組中元素仍是映射到相同的index位置。 // 不然映射到j+oldCap位置。這樣一來就不用從新計算每一個節點的位置了,在java6,java7中須要rehash到新的位置。 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的基本原理搞清楚了,經過源碼對HashMap能夠總結出如下幾點:
鑑於筆者水平有限,以上表述中若有不足之處,請你們點評和修正!
參考資料:
Importnew:http://www.importnew.com/20386.html