Java中的HashMap源碼詳解
HashMap
當(dāng)我們確切知道HashMap將要處理的數(shù)據(jù)量為n時(shí),推薦調(diào)用構(gòu)造函數(shù)public HashMap(int initialCapacity)來(lái)創(chuàng)建 HashMap,這樣就不會(huì)發(fā)生擴(kuò)容。
以上構(gòu)造函數(shù)并沒(méi)有直接將table數(shù)組的大小設(shè)置為給定的initialCapacity參數(shù)的值n,但是會(huì)設(shè)定閾值threshold為大于用戶給定的n的2的乘方的最小值(例如,假如參數(shù)initialCapacity的值是13-16中的任意一個(gè)值,threshold都會(huì)是16)。
而擴(kuò)容的條件會(huì)分兩種情況:
- 當(dāng)我們調(diào)用了如上構(gòu)造函數(shù)時(shí),擴(kuò)容只在size()>=threshold時(shí)發(fā)生,只要我們確認(rèn)實(shí)際的數(shù)據(jù)量不會(huì)大于在構(gòu)造函數(shù)中傳給參數(shù)initialCapacity的值,那么擴(kuò)容就不會(huì)發(fā)生。
- 如果我們調(diào)用的是無(wú)參構(gòu)造函數(shù),那么擴(kuò)容會(huì)發(fā)生在size()>capacity*loadRefactor時(shí)。
Map接口
| keySet | values | size | containsKey | put | remove |
| entrySet | isEmpty | containsValue | get | clear |
以下為部分JDK1.8添加的默認(rèn)方法,default
| getOrdefault(Object o,V v) | replaceAll(BiFunction<K,V,V> f) | remvoe(K k,V v) |
| forEach(BiConsumer<K,V> c) | putIfAbsent(K k,V v) | replace |
Map.Entry接口
此接口是定義在Map接口內(nèi)部的static的接口
| getKey | setValue | comparingByKey | comparingByKey(Comparator c) |
| getValue | equals | comparingByValue | comparingByValue(Comparator c) |
源碼解析
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {定義一些默認(rèn)值
// table的初始大小默認(rèn)值,即桶個(gè)數(shù),必須是2的乘方
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// table的大小的最大值,即桶數(shù)的最大值
static final int MAXIMUM_CAPACITY = 1 << 30;
// 負(fù)載因子,建議0.5-1.5
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 當(dāng)某個(gè)桶內(nèi)元素個(gè)數(shù)大于等于此數(shù),并且桶數(shù)大于64時(shí),會(huì)將桶內(nèi)元素的存儲(chǔ)結(jié)構(gòu)由單鏈表改為紅黑樹(shù)
static final int TREEIFY_THRESHOLD = 8;
// 當(dāng)桶內(nèi)元素個(gè)數(shù)小于或者等于此數(shù)時(shí),會(huì)將桶內(nèi)元素的存儲(chǔ)結(jié)構(gòu)由紅黑樹(shù)改為單鏈表
static final int UNTREEIFY_THRESHOLD = 6;
// 若table的大小小于MIN_TREEIFY_CAPACITY 時(shí),即便某個(gè)桶內(nèi)的元素個(gè)數(shù)達(dá)到了TREEIFY_THRESHOLD 后,也并不會(huì)對(duì)這個(gè)桶做樹(shù)化操作,而是對(duì)map進(jìn)行擴(kuò)容resize()
static final int MIN_TREEIFY_CAPACITY = 64;定義內(nèi)部類:封裝鏈表的節(jié)點(diǎn)
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;
}
}定義實(shí)例域
注意:
- 并沒(méi)有定義一個(gè)capacity實(shí)例域來(lái)指明table數(shù)組的大小,盡管類中定義了一個(gè)靜態(tài)常量DEFAULT_INITIAL_CAPACITY。
- table數(shù)組的大小是在初始化時(shí)確定的:參看resize()方法。
- 所有實(shí)例域的訪問(wèn)控制都是默認(rèn)的
/* ---------------- Fields -------------- */
// 裝桶的數(shù)組,存儲(chǔ)每個(gè)桶內(nèi)的單鏈表的頭結(jié)點(diǎn)或者樹(shù)的根節(jié)點(diǎn)
transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
// Map中當(dāng)前實(shí)際存儲(chǔ)的元素個(gè)數(shù)
transient int size;
// 每次remove,add等都會(huì)++modCount,當(dāng)并發(fā)時(shí),發(fā)現(xiàn)自己的modCount不是原來(lái)的了,就會(huì)拋出異常,表示并行修改失敗
transient int modCount;
// 閾值:當(dāng)map中的元素個(gè)數(shù)大于等于threshold時(shí),會(huì)觸發(fā)resize()操作進(jìn)行擴(kuò)容。
int threshold;
// 負(fù)載因子:當(dāng)用戶調(diào)用的默認(rèn)無(wú)參構(gòu)造函數(shù)、或者map自動(dòng)擴(kuò)容時(shí),新的threshold=新table的capacity*loadFactor;
final float loadFactor;定義構(gòu)造函數(shù)
注意:
如果用戶確切知道將要處理的數(shù)據(jù)量為capacity,則可以調(diào)用構(gòu)造函數(shù)public HashMap(int initialCapacity) ,此構(gòu)造函數(shù)會(huì)設(shè)定閾值threshold為大于用戶給定的capacity的2的乘方的最小值。
因此用戶在主動(dòng)設(shè)定capacity后不必?fù)?dān)心自動(dòng)擴(kuò)容問(wèn)題,因?yàn)閿U(kuò)容只會(huì)在實(shí)際數(shù)據(jù)量>=threshold時(shí)發(fā)生,而此種情況下threshold>=用戶設(shè)定的capacity會(huì)一定成立。 參見(jiàn):tableSizeFor()方法
/* --------------------------構(gòu)造函數(shù),不會(huì)初始化table數(shù)組,table數(shù)組只有在首次調(diào)用put方法時(shí)才會(huì)被初始化------ */
// 默認(rèn)構(gòu)造函數(shù),只設(shè)置了負(fù)載因子的默認(rèn)值
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
// 初始化loadFactor 、threshold 的值
// threshold = 大于initialCapacity的最小的2乘方(如,15 ->16 ,13->16)
public HashMap(int initialCapacity, float loadFactor) {
...
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
// 計(jì)算出大于cap的最小的2的乘方
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1; // 00001 0010 | 0000 1001 -> 11011
n |= n >>> 2; // 0001 1011 | 0000 0110 -> 11111
n |= n >>> 4; // 0001 1111 | 0000 0001 -> 11111
n |= n >>> 8; //
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}put方法
- 如果table還未被初始化,則調(diào)用resize()進(jìn)行初始化
- 如果散列到桶中之后,桶內(nèi)元素個(gè)數(shù)>=TREEIFY_THRESHOLD ,則調(diào)用treeifyBin()方法檢查是否要將桶改為紅黑樹(shù)結(jié)構(gòu)
- 如果散列到Map中之后,Map中元素個(gè)數(shù)>=threshold了,則調(diào)用resize()方法進(jìn)行擴(kuò)容
/* ------------------------------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; // 頭結(jié)點(diǎn)
int n, i; // n:table的大小。i:新節(jié)點(diǎn)的桶號(hào)
// 如果還未被初始化過(guò),則調(diào)用resize(); HashMap在首次調(diào)用put方法之前,是不會(huì)初始化table的,因?yàn)槟菢拥脑挄?huì)浪費(fèi)一塊連續(xù)內(nèi)存。
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 根據(jù)key的哈希值,確定桶號(hào),如果桶中還沒(méi)有元素,則直接將其作為頭結(jié)點(diǎn)存儲(chǔ)到桶中
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 獲取到了頭結(jié)點(diǎn)
else {
Node<K,V> e; // 目標(biāo)節(jié)點(diǎn))
K k;
// 如果頭結(jié)點(diǎn)的key和新節(jié)點(diǎn)的key相同,則頭結(jié)點(diǎn)即為要被取代的目標(biāo)節(jié)點(diǎn)
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 如果頭結(jié)點(diǎn)是TreeNode類型的,則調(diào)用putTreeVal方法將新節(jié)點(diǎn)插入,并返回插入后的目標(biāo)節(jié)點(diǎn)
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 桶還未滿
else {
for (int binCount = 0; ; ++binCount) {
// 目標(biāo)指針指向鏈表中的下一個(gè)元素
if ((e = p.next) == null) {
// 如果沒(méi)有找到key相同的節(jié)點(diǎn),就直接追加到鏈表尾部
p.next = newNode(hash, key, value, null);
// 如果桶中元素?cái)?shù)是達(dá)到了設(shè)定的變樹(shù)閾值(默認(rèn)值8),則需要將桶內(nèi)元素的存儲(chǔ)結(jié)構(gòu)更新為紅黑樹(shù)
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 如果鏈表中有和新節(jié)點(diǎn)的key相同的元素
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// map中有與新節(jié)點(diǎn)的key相同的元素,那么根據(jù)條件做一些操作,就返回
if (e != null) { // existing mapping for key
V oldValue = e.value;
// onlyIfAbsent 是方法參數(shù),表示只有不存在相同key的節(jié)點(diǎn)時(shí),才進(jìn)行更新操作,如果有相同節(jié)點(diǎn),則不做任何操作。
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e); //此處是留給LinkedHashMap用的。
return oldValue;
}
} // else結(jié)束
// 更新了hashMap,就執(zhí)行++modCount;
++modCount;
// 當(dāng)map中的元素?cái)?shù)量大于閾值,就要擴(kuò)容再散列
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}對(duì)table數(shù)組初始化 \ 擴(kuò)容
resize()方法內(nèi)有兩種邏輯:
- 一種是當(dāng)前table為null時(shí),會(huì)對(duì)table進(jìn)行初始化操作;
- 一種是當(dāng)前table非null,會(huì)對(duì)table進(jìn)行擴(kuò)容操作;
final Node<K,V>[] resize() {
// 當(dāng)前table
Node<K,V>[] oldTab = table;
// 當(dāng)前table的大小
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 當(dāng)前的閾值
int oldThr = threshold;
int newCap, newThr = 0;
// oldCap>0,說(shuō)明是要做擴(kuò)容操作
if (oldCap > 0) {
// 如果原本的table的大小已經(jīng)是最大值,無(wú)法繼續(xù)擴(kuò)容,直接退出
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 擴(kuò)容:設(shè)置新的table的大小為原來(lái)的2倍,新的threshold也為原來(lái)的2背
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// oldCap<= 0,說(shuō)明table還未被初始化過(guò),要進(jìn)行初始化table的操作;oldThr>0,說(shuō)明用戶調(diào)用的有參構(gòu)造函數(shù),設(shè)置了threshold;直接將根據(jù)用戶參數(shù)計(jì)算出的閾值設(shè)定為table的大小
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// oldCap<= 0,說(shuō)明是要進(jìn)行初始化table的操作;oldThr<0,說(shuō)明用戶調(diào)用的默認(rèn)無(wú)參構(gòu)造函數(shù);則將各個(gè)域變量的值設(shè)置為默認(rèn)值。
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 如果經(jīng)過(guò)以上設(shè)置,newThr 仍為0,(什么情況下會(huì)出現(xiàn)?)
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
// 無(wú)論是要初始化table,還是要對(duì)table進(jìn)行擴(kuò)容,經(jīng)過(guò)以上邏輯,都已經(jīng)確定了要新創(chuàng)建的table的大小、threshold 。
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// 如果當(dāng)前table不為null,說(shuō)明需要進(jìn)行擴(kuò)容操作
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;
}
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)于Java中的HashMap源碼詳解的文章就介紹到這了,更多相關(guān)HashMap源碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Kotlin?標(biāo)準(zhǔn)函數(shù)和靜態(tài)方法示例詳解
這篇文章主要為大家介紹了Kotlin?標(biāo)準(zhǔn)函數(shù)和靜態(tài)方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
Spring中的@PostConstruct注解使用方法解析
這篇文章主要介紹了Spring中的@PostConstruct注解使用方法解析,@PostConstruct注解是用來(lái)處理在@Autowired注入屬性后init()方法之前,對(duì)一些零散的屬性進(jìn)行賦值的注解,需要的朋友可以參考下2023-11-11
Java中MapStruct復(fù)制對(duì)象的具體使用
MapStruct是一個(gè)用于Java的代碼生成器,可以自動(dòng)生成類型安全的Bean映射代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-12-12
SpringBoot項(xiàng)目依賴和配置最新示例講解
這篇文章主要介紹了SpringBoot項(xiàng)目依賴和配置,這里主要是搭建項(xiàng)目常用到的maven依賴以及搭建項(xiàng)目會(huì)需要用到的一些配置文件,本文通過(guò)示例代碼給大家詳細(xì)講解,需要的朋友可以參考下2022-11-11
Java嵌入式開(kāi)發(fā)的優(yōu)勢(shì)及有點(diǎn)總結(jié)
在本篇內(nèi)容里小編給大家整理了關(guān)于Java嵌入式開(kāi)發(fā)的優(yōu)勢(shì)及相關(guān)知識(shí)點(diǎn)內(nèi)容,有興趣的朋友們學(xué)習(xí)下。2022-11-11
Java中JDK動(dòng)態(tài)代理的超詳細(xì)講解
JDK 的動(dòng)態(tài)代理是基于攔截器和反射來(lái)實(shí)現(xiàn)的,JDK代理是不需要第三方庫(kù)支持的,只需要JDK環(huán)境就可以進(jìn)行代理,下面這篇文章主要給大家介紹了關(guān)于Java中JDK動(dòng)態(tài)代理的超詳細(xì)講解,需要的朋友可以參考下2022-10-10

