前言
還是需要從頭閱讀下HashMap的源碼。目標在於更好的理解HashMap的用法,學習更精煉的編碼規范,以及應對面試。
它根據鍵的hashCode值存儲數據,大多數情況下可以直接定位到它的值,因而具有很快的訪問速度,但遍歷順序卻是不確定的。 HashMap最多只允許一條記錄的鍵為null,允許多條記錄的值為null。HashMap非線程安全,即任一時刻可以有多個線程同時寫HashMap,可能會導致數據的不一致。如果需要滿足線程安全,可以用 Collections的synchronizedMap方法使HashMap具有線程安全的能力,或者使用ConcurrentHashMap。
面試官: 說說HashMap的原理
答: HashMap是通過哈希表的數組鏈表實現的。內部維護一個Node數組,
當put時,計算key hash后的值當做索引。如果數組中該位置為null,則放入value。然后判斷是否需要擴容,返回null。
如果數組上已經有元素,判斷hash和key是否相等,相等就表示找到node節點了,不相等則判斷該元素是TreeNode還是普通Node。
如果是TreeNode,則按照TreeNode的put方法插入。
如果不是TreeNode, 遍歷鏈表,對比hash和key,若都不相等,則插入隊尾,如果鏈表長度大於等於8,將鏈表轉換為TreeNode.
找到node之后,node不為null則賦值value。最后返回原來的value。
完畢。
面試官: 如何擴容
答:(直接說1.8的內容,想要裝逼體驗深度就對比1.7. 比如1.7擴容會導致鏈表重排倒置,1.8不會,1.8不用再次計算hash等。當然,這樣回答要准備好繼續入坑,為什么,如何做到)
要說擴容,首先要知道原來的容量以及什么時候擴容。HashMap初始化的時候可以指定initialCapacity
和loadfactor
。capacity
是2的指數倍,表示數組的長度。
loadfactor
表示達到容量的百分比后擴容。threshold=capacity*loadfactor
就是HashMap對象中可以容納的最大K-V鍵值對數量。
所以,當size(當前K-V鍵值對數量)超過threshold
,則進行擴容。當然,如果capacity已經大於2^30,則直接將threshold=Integer.MAX_VALUE
, 就不擴容了,碰撞吧。
擴容的時候先計算容量,擴大為原來的2倍,對應threshold
也擴大為原來的2倍。
然后將原來數組上的元素復制到新的數組。對於沖突碰撞的結點,是TreeNode則按TreeNode插入,不是TreeNode則將鏈表的一半平分到其他新增的索引位置。
關於幾個數字。loadfactor=0.75; DEFAULT_INITIAL_CAPACITY = 1 << 4; MAXIMUM_CAPACITY = 1 << 30; TREEIFY_THRESHOLD = 8
。也就是說,對於我們平時直接new 的HashMap對象,默認數組長度為16,最大容納12個,超過12個則擴容;當發生碰撞的數量小於8個則維護鏈表,當數量大於8個則改造成TreeNode.
面試官: 說TreeNode是怎么put的
紅黑樹啊,紅黑樹我不會寫。
面試官: 如何get
答: 既然知道HashMap的存儲原理,那個get也就呼之欲出了。 首先,計算hash索引,如果頭結點不為null,如果頭結點hash以及key都相等,則取出。
如果頭結點不相等,並且next不為nul,判斷next是否是TreeNode, 如果是TreeNode則TreeNode get.
如果不是TreeNode, 遍歷鏈表,找到hash和key相等的取出value。
在這里,非常感謝美團技術博客中的《Java 8系列之重新認識HashMap》, 深入,透徹,易懂。
面試官: HashMap是線程安全的嗎
答:不是,高並發中不僅會不安全,還有可能造成死循環(擴容的時候)。想要在並發中使用,請使用ConcurrentHashMap.
初始化,構造函數
HashMap<String, Object> map = new HashMap<>();
對應源碼為:
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
構造一個空的HashMap,默認容量(capacity)為16,默認負載因子(load factor)是0.75.
Put
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
- put的key需要計算hashcode
- put的value可以是任何對象
- 如果key存在則替換並返回前一個對象
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
重新計算hash,但仍舊根據key的hashcode的方法。
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//....
}
- 核心put方法,第一個參數是key的hash之后再hash. 這里,我開始有個疑問,就是發現所有調用putVal的地方的第一個參數的hash的計算方式都是一樣的,覺得應該去掉第一個參數,直接在這個方法里
hash(Key)
就好了。事實上,確實可以這么做,但帶來的問題是所有調用這個方法的地方都要用同樣的hash方法。 - 第二個參數是key
- 第三個參數是value
- 第4個參數是區分
putIfAbsent(k,v)
的標志,true表示如果不存在則存儲,已經存在則不存儲;默認false,即覆蓋。 - 第5個參數
evict
是逐出的意思,只在LinkedHashMap中有用,本處空調用。
存儲原理概述
首先,需要准備背景知識,關於數字二進制表示,左移右移等。參閱 http://www.cnblogs.com/woshimrf/p/operation-bit.html 。
PutVal()
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//內部數組
Node<K,V>[] tab;
//指針
Node<K,V> p;
//數組長度,索引
int n, i;
//初始化數組,對於新建的對象,沒有put的時候是沒有創建數組的
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//計算索引,若當前結點為null,則直接直插入,完畢到返回。
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k; //e找到的結點,
//如果當前結點hash相同,key相同,則找到結點
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 {
//遍歷鏈表,p是指針,e為找到的結點
for (int binCount = 0; ; ++binCount) {
//遍歷到尾結點后直接插入尾部新結點,此時e==null, 不參與后面的value覆蓋邏輯。
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st, 當鏈表長度大於8后轉換為紅黑樹
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//找到結點后決定是否覆蓋value
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;//統計數組上的結點數量
if (++size > threshold) //當前K-V數量超過threshold后擴容
resize();
afterNodeInsertion(evict);
return null; //因為執行到此處的代碼都是新插入的結點,所以返回空。
}
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 { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
//出現了,threshold的計算公式
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
//用新的capacity來創建數組
@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 { // preserve order 對於碰撞的鏈表,優化,取出一半的結點到新的數組結點
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;
}