HashMap
參考:http://blog.csdn.net/jeffleo/article/details/54946424
http://blog.csdn.net/qq_27093465/article/details/52207135
1.HashMap的定義和構造函數
底層實現原理是:數組 + 鏈表 + 紅黑樹
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
HashMap繼承自AbstractMap,AbstractMap是Map接口的骨幹實現,AbstractMap中實現了Map中最重要最常用的方法,這樣HashMap繼承AbstractMap就不需要實現Map的所有方法了,讓HashMap減少了大量的工作。這裏實現Map接口,沒有什麼作用,應該是爲了讓Map的層次結構更加清晰。
2.HashMap的成員變量
默認初始化大小
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
加載因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
Node類型的數組,HashMap用這個來維護內部的數據結構,它的長度由容量決定
transient Node<K,V>[] table;
HashMap的大小
transient int size;
HashMap的極限容量,擴容臨界點(容量*加載因子)
int threshold;
3.HashMap的四個構造函數
3.1 構造一個具有默認初始容量(16)和默認加載因子(0.75)的空HashMap
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
3.2 構造一個帶指定初始容量和默認加載因子(0.75)的空HashMap
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
3.3構造一個帶指定初始容量和加載因子的空HashMap
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);
}
3.4 構造一個映射關係與指定Map的相同的新HashMap
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
容量:initialCapacity,哈希表中桶的數量,初始容量只是哈希表在創建時的容量,實際上就是Node<K,V>[] table的容量。
加載因子:loadFactor。在哈希表在其容量自動增加之前可以達到多滿的一種尺度。它衡量的是一個散列表的空間的使用程度,負載因子越大表示散列表的裝填程度越高,反之越小。對於使用鏈表法的散列表來說,查找一個元素的平均時間是O(1+a),因此如果負載因子越大,對控件的利用更充分,然而後果是查找效率的降低;如果負載因子太小,那麼散列表的數據將過於稀疏,對控件造成嚴重浪費。系統默認負載因子爲0.75,一般情況下是無需修改的。
當哈希表中的條目數超出了加載因子與當前容積的乘積時,則要對哈希表進行refresh操作(即重建內部數據結構),從而哈希表將具有大約兩倍的桶數。
4.HashMap的數據結構
HashMap是一個“鏈表散列”,數據結構如下所示:
說明:上圖中的Entry<K,V>實際上應該是Node<K,V>。
HashMap的構造函數的源碼:
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0) //容量不能小於0
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY) //容量不能超出最大容量
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor)) //加載因子不能小於等於0 或者 爲非數字
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor; //設置加載因子
this.threshold = tableSizeFor(initialCapacity);//設置容量大小
}
//計算大於初始容量的最小的2次方作爲哈希表table的長度,其中|是或運算,>>> 是無符號右移
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
方法的運行結果:cap爲21,結果爲32.
這樣計算hash值的目的是爲了讓hash發生碰撞的概率比較小,這樣就會使得數據在table數組中分佈比較均勻,查詢速度比較快。
在HashMap內部還有一個Node數組,內部結構:
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;
}
}
說明:Node類實現了Map.Entry接口,是HashMap的內部類,也是維護着一個key-value映射關係,除了key和value,還有next引用(該引用指向當前table位置的鏈表),hash值用來確定每一個Node鏈表在table中的位置。
5.HashMap的存儲實現put(K,V) 解決衝突使用的是鏈地址法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//根據key獲取對應的hash值,如果key爲空,得到的就是0;如果不爲空,就得到的是key的hash值的h右移16位次方
//所以這裏可以得到,當輸入的key爲null的時候,插入的都是數組第一個位置,也就是Node
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//參數說明:hash:key的hash值;key:傳入的key;value:傳入的value;
//onlyIfAbsent:如果爲真,不改變存在的值;evict:如果爲false,表格處於創建模式。
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//tab是存儲Node數組的,p是存儲hash值對應的Node數組位置的頭節點,n是存儲數組的長度,i是hash對應的位置
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0) //如果table爲空或者長度爲0,就重新設置表
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null) //如果hash值所在的位置爲空
tab[i] = newNode(hash, key, value, null);//新增節點,並放入table中
else { //hash值所在的位置不爲空,就添加到鏈表的前面
Node<K,V> e; K k;
if (p.hash == hash && //判斷p位置的第一個節點key是否和傳入的key相同
((k = p.key) == key || (key != null && key.equals(k))))
e = p; //相同就把p賦值給e
else if (p instanceof TreeNode) //判斷p是否是紅黑樹節點
//將新的key-value添加進入紅黑樹中
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); //直接新增節點放在p的後面
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash); //替換在hash位置的鏈表中所有連接的節點
break;
}
if (e.hash == hash && //當前節點的key就是待存入的key
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null) //原始的值爲空,可以寫入新的值
e.value = value; //將value值寫入節點中
afterNodeAccess(e); //一個回調方法
return oldValue; //返回最初的值
}
}
++modCount; //該HashMap被修改的次數加1
if (++size > threshold) //如果map中有的key-value的對數大於容量*加載因子,就重新設置map集合
resize();
afterNodeInsertion(evict); //一個回調方法,節點插入之後的回調
return null;
}
//將key-value放入hashmap中,是putval的tree版本
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this; //獲取根節點
for (TreeNode<K,V> p = root;;) { //指向根節點
int dir, ph; K pk;
if ((ph = p.hash) > h) //根節點的hash值大於待存入的hash值
dir = -1;
else if (ph < h) //根節點的hash值小於待存入的hash值
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk))) //查找到節點,直接返回
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) { //未找到
TreeNode<K,V> q, ch; //ch存儲p個左節點,q存儲給定的key-value在p中的開始節點
searched = true;
//在p的左邊或者右邊找到給定的key-value節點,直接返回找到的節點q
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
//判斷給定的hash應該放在左邊還是右邊,如果根節點hash值大,也就是dir<0,就將傳入的key-value放在左邊,
//否則放在右邊.總之是升序排列
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn); //新的節點
if (dir <= 0) //放在根節點的左邊
xp.left = x;
else
xp.right = x;
xp.next = x; //將x放在根節點的下一個節點,即鏈表的頭結點處
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
moveRootToFront(tab, balanceInsertion(root, x));//確保給定的根節點是鏈表的第一個節點
return null;
}
}
}
//建立一個新的節點
Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
return new Node<>(hash, key, value, next);
}
//樹節點的靜態內部類
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links //紅黑樹
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);
}
/**
* Returns root of tree containing this node.
*/
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
}
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) //判斷鏈表長度
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
/**
* Returns root of tree containing this node.
*/
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
6.HashMap的獲取實現get(Object key)
public V get(Object key) {
Node<K,V> e;
//首先 e = getNode(hash(key), key)找到對應key的節點,然後如果爲null,就返回null,找到節點就返回對應的value
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;
//判斷table是否存有數據
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; //一直未找到,直接返回null
}
final TreeNode<K,V> getTreeNode(int h, Object k) {
return ((parent != null) ? root() : this).find(h, k, null);
}
7.Fail-Fast機制:
HashMap不是線程安全的,因此如果在使用迭代器的過程中有其他線程修改了map,那麼將拋出ConcurrentModificationException,這就是所謂Fail-Fast策略。
通過源碼中的 modCount域實現,modCount記錄修改次數,對HashMap內容的修改都將增加這個值,那麼在迭代器初始化過程中會將這個值賦給迭代器的expectedModCount。
abstract class HashIterator {
Node<K,V> next; // next entry to return
Node<K,V> current; // current entry
int expectedModCount; // for fast-fail ,實現了Fast-Fail機制
int index; // current slot
HashIterator() {
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
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;
}
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
//判斷是否相等,如果不相等就說明在迭代過程中有其他線程對數據進行了修改,直接拋出異常。
//所以modCount也要聲明爲volatile,保證線程之間修改的可見性
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}
public final void remove() {
Node<K,V> p = current;
if (p == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
K key = p.key;
removeNode(hash(key), key, null, false, false);
expectedModCount = modCount;
}
}
**
##總結:
由所有HashMap類的“Collection視圖方法”所返回的迭代器都是快速失敗的: 在迭代器創建之後,如果從結構上對映射進行修改,除非通過迭代器本身的remove方法,其他任何時間任何方式的修改,迭代器都將拋出ConcurrentModificationException。
因此,面對併發的修改,迭代器很快就會完全失敗,而不冒在將來不確定的時候發生任意不確定行爲的冒險。 但是,迭代器的快速失敗行爲不能得到保證,一般來說,存在非同步的併發修改時,不可能作出任何堅決的保證。 快速失敗迭代器盡最大努力拋出ConcurrentModificationException。
因此,編寫依賴於此異常的程序的做法是錯誤的,正確做法是:迭代器的快速失敗行爲應該僅用於檢測程序錯誤。
**