序
閱讀java源碼可能是每一個(gè)java程序員的必修課饮寞,只有知其所以然,才能更好的使用java,寫(xiě)出更優(yōu)美的程序疯兼,閱讀java源碼也為我們后面閱讀java框架的源碼打下了基礎(chǔ)。閱讀源代碼其實(shí)就像再看一篇長(zhǎng)篇推理小說(shuō)一樣贫途,不能急于求成吧彪,需要慢慢品味才行。這一系列的文章丢早,記錄了我閱讀源碼的收獲與思路姨裸,讀者也可以借鑒一下,也僅僅是借鑒怨酝,問(wèn)渠那得清如許傀缩,絕知此事要躬行!要想真正的成為大神农猬,還是需要自己親身去閱讀源碼而不是看幾篇分析源碼的博客就可以的赡艰。
正文
HashMap是我們經(jīng)常用的的一個(gè)集合類,其中java對(duì)于Hash散列表的維護(hù)斤葱、大小的動(dòng)態(tài)擴(kuò)展以及解決Hash沖突的方法都是值得我們借鑒的慷垮。如何更好地使用HashMap揖闸,建議大家把JAVA API文檔拿來(lái)讀讀,其中對(duì)于如何很好的使用HashMap做了詳細(xì)的說(shuō)明料身,在一個(gè)是將HashMap的源代碼自行分析一遍汤纸。
總結(jié)
JAVA8中對(duì)HashMap的優(yōu)化
通過(guò)閱讀源碼,我們可以了解到惯驼,在java1.8這個(gè)版本中蹲嚣,SUN大神們?yōu)閔ashmap的查詢進(jìn)行了進(jìn)一步優(yōu)化,原來(lái)hashmap是hash表+鏈表的形式祟牲,在1.8中變?yōu)榱薶ash表+鏈表/樹(shù)的形式隙畜,即在一定條件下同一hash值對(duì)應(yīng)的鏈表會(huì)被轉(zhuǎn)化為樹(shù),進(jìn)而優(yōu)化了查詢。通過(guò)這次學(xué)習(xí)Hashmap的源碼實(shí)現(xiàn)说贝,我們可以學(xué)習(xí)到如何利用樹(shù)來(lái)對(duì)數(shù)組查找進(jìn)行優(yōu)化议惰。那么何時(shí)樹(shù)化?何時(shí)調(diào)整表的大邢缢 言询?
在HashMap的類成員中,有一個(gè)叫做MIN_TREEIFY_CAPACITY的常量傲宜,它規(guī)定了當(dāng)HashMap被使用的空間大小超過(guò)這個(gè)常量的值時(shí)运杭,才會(huì)開(kāi)始樹(shù)化。而針對(duì)每一個(gè)hash值對(duì)應(yīng)的鏈表函卒,有一個(gè)叫TREEIFY_THRESHOLD
常量辆憔,規(guī)定了當(dāng)鏈表的大小超過(guò)其時(shí),就對(duì)此鏈表進(jìn)行樹(shù)化报嵌。
源碼分析
HashMap關(guān)鍵的變量:
/**
* The default initial capacity - MUST be a power of two.
*
* HashMap中哈希表的初始容量默認(rèn)值
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*
* 哈希表的最大容量
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
*
* 負(fù)載因子的默認(rèn)值
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*
* 將鏈表樹(shù)化的閥值虱咧,即當(dāng)鏈表存儲(chǔ)量達(dá)到多大時(shí),將其轉(zhuǎn)化為樹(shù)
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*
* 將樹(shù)轉(zhuǎn)化為鏈表的閥值锚国。
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
*
* 這個(gè)字段決定了當(dāng)hash表的至少大小為多少時(shí)腕巡,鏈表才能進(jìn)行樹(shù)化。這個(gè)設(shè)計(jì)時(shí)合理的血筑,
* 因?yàn)楫?dāng)hash表的大小很小時(shí)绘沉,這時(shí)候表所需的空間還不多,可以犧牲空間減少時(shí)間豺总,所以這個(gè)情況下
* 當(dāng)存儲(chǔ)的節(jié)點(diǎn)過(guò)多時(shí)梆砸,最好的辦法是調(diào)整表的大小,使其增大园欣,而不是將鏈表樹(shù)化。
*
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*
* hash表
*/
transient Node<K,V>[] table;
/**
* The number of key-value mappings contained in this map.
* Hashmap當(dāng)前的大小
*/
transient int size;
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*
*/
transient int modCount;
/**
* The next size value at which to resize (capacity * load factor).
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
//閥值休蟹,它決定了hashmap何時(shí)進(jìn)行擴(kuò)容沸枯。
int threshold;
/**
* The load factor for the hash table.
* 負(fù)載因子日矫,用于計(jì)算閥值,它等于threshold與hashmap當(dāng)前容量的比例绑榴。
* @serial
*/
final float loadFactor;
再介紹了hashmap的重要變量之后哪轿,我們就可以看看其最關(guān)鍵的put()方法與resize()方法了:
put():
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* 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) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果還沒(méi)有為hash表申請(qǐng)空間,那么就使用resize()方法初始化hash表翔怎。
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//如果沒(méi)有發(fā)生hash沖突窃诉,則直接將數(shù)據(jù)存入hash表中
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//如果發(fā)生了沖突
else {
Node<K,V> e; K k;
//判斷是否與鏈表頭結(jié)點(diǎn)相同
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//判斷當(dāng)前要插入的鏈表表示的結(jié)構(gòu)是否是樹(shù),如果是則交給putTreeVal()處理
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//當(dāng)要插入的數(shù)據(jù)不是頭結(jié)點(diǎn)赤套,并且鏈表沒(méi)有被樹(shù)化的情況下
else {
//遍歷鏈表飘痛,判斷是做修改還是插入操作
for (int binCount = 0; ; ++binCount) {
//如果是插入操作
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//判斷是否達(dá)到樹(shù)化的標(biāo)準(zhǔn)
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash); //樹(shù)化鏈表
break;
}
//發(fā)現(xiàn)當(dāng)前鏈表中的結(jié)點(diǎn)有與要插入的數(shù)據(jù)相同的key,跳出循環(huán)進(jìn)行修改操作
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//修改操作容握,宣脉,進(jìn)行Value數(shù)據(jù)的修改
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
//此方法是在LinkedHashMap中實(shí)現(xiàn)的,在HashMap中為空
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//判斷put()后是否需要擴(kuò)容
if (++size > threshold)
resize();
//此方法是在LinkedHashMap中實(shí)現(xiàn)的剔氏,在HashMap中為空
afterNodeInsertion(evict);
return null;
}
這里需要注意幾點(diǎn):
1.為什么在查找插入數(shù)據(jù)在hash表中相應(yīng)位置時(shí)塑猖,使用的是hash(key)&(length-1)而不是hash(key)?
因?yàn)閔ash(key)的值是隨機(jī)的,無(wú)法確定其范圍谈跛,通過(guò)&操作羊苟,相當(dāng)于對(duì)hash表的長(zhǎng)度取模,能夠在保證數(shù)據(jù)隨機(jī)均勻的分布在hash表中感憾,并且限制hash值的范圍蜡励。
2.因?yàn)殒湵淼拇嬖冢岳碚撋蟞ashmap的容量是沒(méi)有上限的吹菱,但是當(dāng)hash表無(wú)法繼續(xù)擴(kuò)充時(shí)巍虫,隨著存儲(chǔ)數(shù)據(jù)的增加,其查找效率會(huì)逐漸降低鳍刷。
3.負(fù)載因子的作用:負(fù)載因子占遥,其實(shí)表達(dá)的都是HashMap容量空間的占有程度,它存在的意義是為了協(xié)調(diào)查找效率與空間利用率之間的平衡输瓜。Capacity*loadFactor=threshold摹察,threshold其實(shí)就表示了hashmap的真實(shí)容量大小,而Capacity則是hash表的長(zhǎng)度买喧。負(fù)載因子越大則代表容量空間的占有程度高姨俩,也就是能容納更多的元素,元素多了北戏,鏈表大了负芋,所以此時(shí)查找效率就會(huì)降低。反之嗜愈,負(fù)載因子越小則鏈表中的數(shù)據(jù)量就越稀疏旧蛾,此時(shí)會(huì)對(duì)空間造成爛費(fèi)莽龟,但是此時(shí)查找效率高。
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;
//先確定新表的hash表長(zhǎng)度與閥值锨天。
if (oldCap > 0) {
//判斷當(dāng)前hash表的長(zhǎng)度是否已經(jīng)達(dá)到上限毯盈,如果是則將閥值設(shè)置為Integer.MAX_VALUE并返回
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//將容量大小增加為原來(lái)的二倍,并計(jì)算相應(yīng)的閥值
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"})
//在確定hash表長(zhǎng)度后病袄,創(chuàng)建新表搂赋,將舊表中的數(shù)據(jù)進(jìn)行遷移到新表。
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;
//判斷是否已經(jīng)樹(shù)化益缠,如果是則調(diào)用樹(shù)化的相應(yīng)方法進(jìn)行數(shù)據(jù)遷移
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//非樹(shù)化鏈表的情況
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
//這里的代碼需要好好看脑奠,就是因?yàn)榇颂帉?shí)現(xiàn)方式的原因,
//導(dǎo)致了hashmap遍歷時(shí)不能保證數(shù)據(jù)能夠一直按照插入或者修改的順序訪問(wèn)左刽。
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;
}
關(guān)于resize需要注意的是:
1.resize擴(kuò)容后的容量是原來(lái)的兩倍捺信,直到容量達(dá)到最大,這時(shí)就會(huì)更改閾值來(lái)繼續(xù)擴(kuò)容欠痴。
2.正是因?yàn)閞esize的擴(kuò)容原理迄靠,導(dǎo)致了Hashmap不能保證插入數(shù)據(jù)的順序性,當(dāng)然如果一定要保證喇辽,我們可以使用LinkedHashMap