Java1.7全網(wǎng)最深入HashMap源碼解析

存儲(chǔ)結(jié)構(gòu)
內(nèi)部包含了一個(gè) Entry 類(lèi)型的數(shù)組 table。Entry 存儲(chǔ)著鍵值對(duì)。它包含了四個(gè)字段,從 next 字段我們可以看出 Entry 是一個(gè)鏈表。即數(shù)組中的每個(gè)位置被當(dāng)成一個(gè)桶,一個(gè)桶存放一個(gè)鏈表。HashMap 使用拉鏈法來(lái)解決沖突,同一個(gè)鏈表中存放哈希值和散列桶容量取模運(yùn)算結(jié)果相同的 Entry。

啊啊
transient Entry[] table; //位桶數(shù)組
/**
* Entry類(lèi)實(shí)現(xiàn)了Map.Entry接口
* 即 實(shí)現(xiàn)了getKey()、getValue()、equals(Object o)和hashCode()等方法
**/
static class Entry<K,V> implements Map.Entry<K,V> {
final K key; // 鍵
V value; // 值
Entry<K,V> next; // next指針
int hash; //hashCode()方法計(jì)算出的hash值
/**
* 構(gòu)造方法,創(chuàng)建一個(gè)Entry
* 參數(shù):哈希值h,鍵值k,值v、下一個(gè)節(jié)點(diǎn)n
*/
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
// 返回 與 此項(xiàng) 對(duì)應(yīng)的鍵
public final K getKey() {
return key;
}
// 返回 與 此項(xiàng) 對(duì)應(yīng)的值
public final V getValue() {
return value;
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
/**
* equals()
* 作用:判斷2個(gè)Entry是否相等,必須key和value都相等,才返回true
*/
public final boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
Object k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}
/**
* hashCode()
*/
public final int hashCode() {
return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
}
public final String toString() {
return getKey() + "=" + getValue();
}
/**
* 當(dāng)向HashMap中添加元素時(shí),即調(diào)用put(k,v)時(shí),
* 對(duì)已經(jīng)在HashMap中k位置進(jìn)行v的覆蓋時(shí),會(huì)調(diào)用此方法
* 此處沒(méi)做任何處理
*/
void recordAccess(HashMap<K,V> m) {
}
/**
* 當(dāng)從HashMap中刪除了一個(gè)Entry時(shí),會(huì)調(diào)用該函數(shù)
* 此處沒(méi)做任何處理
*/
void recordRemoval(HashMap<K,V> m) {
}
}
屬性成員
// 1. 容量(capacity): HashMap中數(shù)組的長(zhǎng)度
// a. 容量范圍:必須是2的冪 & <最大容量(2的30次方)
// b. 初始容量 = 哈希表創(chuàng)建時(shí)的容量
// 默認(rèn)容量 = 16 = 1<<4 = 00001中的1向左移4位 = 10000 = 十進(jìn)制的2^4=16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量 = 2的30次方(若傳入的容量過(guò)大,將被最大值替換)
static final int MAXIMUM_CAPACITY = 1 << 30;
// 2. 加載因子(Load factor):HashMap在其容量自動(dòng)增加前可達(dá)到多滿的一種尺度
// a. 加載因子越大、填滿的元素越多 = 空間利用率高、但沖突的機(jī)會(huì)加大、查找效率變低(因?yàn)殒湵碜冮L(zhǎng)了)
// b. 加載因子越小、填滿的元素越少 = 空間利用率小、沖突的機(jī)會(huì)減小、查找效率高(鏈表不長(zhǎng))
// 實(shí)際加載因子
final float loadFactor;
// 默認(rèn)加載因子 = 0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 3. 擴(kuò)容閾值(threshold):當(dāng)哈希表的大小 ≥ 擴(kuò)容閾值時(shí),就會(huì)擴(kuò)容哈希表(即擴(kuò)充HashMap的容量)
// a. 擴(kuò)容 = 對(duì)哈希表進(jìn)行resize操作(即重建內(nèi)部數(shù)據(jù)結(jié)構(gòu)),從而哈希表將具有大約兩倍的桶數(shù)
// b. 擴(kuò)容閾值 = 容量 x 加載因子
int threshold;
//默認(rèn)的threshold值
static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
// 4. 其他
// 存儲(chǔ)數(shù)據(jù)的Entry類(lèi)型 數(shù)組,長(zhǎng)度 = 2的冪
// HashMap的實(shí)現(xiàn)方式 = 拉鏈法,Entry數(shù)組上的每個(gè)元素本質(zhì)上是一個(gè)單向鏈表
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
//HashMap內(nèi)部的存儲(chǔ)結(jié)構(gòu)是一個(gè)數(shù)組,此處數(shù)組為空,即沒(méi)有初始化之前的狀態(tài)
static final Entry<?,?>[] EMPTY_TABLE = {};
// HashMap的大小,即 HashMap中存儲(chǔ)的鍵值對(duì)的數(shù)量
transient int size;
構(gòu)造函數(shù):
- 構(gòu)造函數(shù)僅用于接收初始容量大?。?code>capacity)、負(fù)載因子(
Load factor),但仍無(wú)真正初始化哈希表(存儲(chǔ)數(shù)組table) - 此處先給出結(jié)論:真正初始化存儲(chǔ)數(shù)組
table是在第1次調(diào)用put()添加鍵值對(duì)時(shí)
/**
* 構(gòu)造函數(shù)1:默認(rèn)構(gòu)造函數(shù)(無(wú)參)
實(shí)際上是調(diào)用構(gòu)造函數(shù)3:指定“容量大小”和“加載因子”的構(gòu)造函數(shù)
*/
public HashMap() {
// 傳入默認(rèn)的容量(16)和負(fù)載因子(0.75)
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
/**
* 構(gòu)造函數(shù)2:指定“容量大小”的構(gòu)造函數(shù)
實(shí)際上是調(diào)用指定“容量大小”和“加載因子”的構(gòu)造函數(shù)
*/
public HashMap(int initialCapacity) {
// 傳入指定的容量,和默認(rèn)的負(fù)載因子
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 構(gòu)造函數(shù)3:指定“容量大小”和“加載因子”的構(gòu)造函數(shù)
* 加載因子 & 容量都由自己指定
*/
public HashMap(int initialCapacity, float loadFactor) {
// HashMap的最大容量只能是MAXIMUM_CAPACITY,哪怕傳入的 > 最大容量
//如果大于最大容量,還是賦值為1 << 30
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
// 設(shè)置 加載因子
this.loadFactor = loadFactor;
// 設(shè)置 擴(kuò)容閾值 = 初始容量
// 注:此處不是真正的閾值,是為了擴(kuò)展table,該閾值后面會(huì)重新計(jì)算
threshold = initialCapacity;
init(); // 一個(gè)空方法用于未來(lái)的子對(duì)象擴(kuò)展
}
/**
* 構(gòu)造函數(shù)4:包含“子Map”的構(gòu)造函數(shù)
* 即 構(gòu)造出來(lái)的HashMap包含傳入Map的映射關(guān)系
* 加載因子 & 容量 = 默認(rèn)
*/
public HashMap(Map<? extends K, ? extends V> m) {
// 設(shè)置容量大小 & 加載因子 = 默認(rèn)
this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
// 該方法用于初始化 數(shù)組 & 閾值,下面會(huì)詳細(xì)說(shuō)明
inflateTable(threshold);
// 將傳入的子Map中的全部元素逐個(gè)添加到HashMap中
putAllForCreate(m);
}
}
hash方法
hash(Object k):計(jì)算key的hash值
該函數(shù)在JDK 1.7 和 1.8 中的實(shí)現(xiàn)不同,但原理(擾動(dòng)函數(shù))一樣使得根據(jù)key生成的哈希碼(hash值)分布更加均勻、更具備隨機(jī)性,避免出現(xiàn)hash值沖突(即指不同key但生成同1個(gè)hash值)
- JDK 1.7 做了9次擾動(dòng)處理 = 4次位運(yùn)算 + 5次異或運(yùn)算
- JDK 1.8 簡(jiǎn)化了擾動(dòng)函數(shù) = 只做了2次擾動(dòng) = 1次位運(yùn)算 + 1次異或運(yùn)算
/**
* 確定位桶數(shù)組下標(biāo)主要分為2步:計(jì)算hash值、根據(jù)hash值再計(jì)算得出最后數(shù)組位置
*/
// a. 根據(jù)鍵值key計(jì)算hash值 ->> 分析1
int hash = hash(key);
// b. 根據(jù)hash值 最終獲得 key對(duì)應(yīng)存放的數(shù)組Table中位置 ->> 分析2
int i = indexFor(hash, table.length);
// JDK 1.7實(shí)現(xiàn):將 鍵key 轉(zhuǎn)換成 哈希碼(hash值)操作 = 使用hashCode() + 4次位運(yùn)算 + 5次異或運(yùn)算(9次擾動(dòng))
static final int hash(int h) {
h ^= k.hashCode();
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
// JDK 1.8實(shí)現(xiàn):將 鍵key 轉(zhuǎn)換成 哈希碼(hash值)操作 = 使用hashCode() + 1次位運(yùn)算 + 1次異或運(yùn)算(2次擾動(dòng))
// 1. 取hashCode值: h = key.hashCode()
// 2. 高位參與低位的運(yùn)算:h ^ (h >>> 16)
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
// a. 當(dāng)key = null時(shí),hash值 = 0,所以HashMap的key 可為null
// 注:對(duì)比HashTable,HashTable對(duì)key直接hashCode(),若key為null時(shí),會(huì)拋出異常,所以HashTable的key不可為null
// b. 當(dāng)key ≠ null時(shí),則通過(guò)先計(jì)算出 key的 hashCode()(記為h),然后 對(duì)哈希碼進(jìn)行 擾動(dòng)處理: 按位 異或(^) 哈希碼自身右移16位后的二進(jìn)制
}
/**
* 函數(shù)源碼分析2:indexFor(hash, table.length)
* JDK 1.8中實(shí)際上無(wú)該函數(shù),但原理相同,即具備類(lèi)似作用的函數(shù)
*/
static int indexFor(int h, int length) {
return h & (length-1);
// 將對(duì)哈希碼擾動(dòng)處理后的結(jié)果 與運(yùn)算(&) (數(shù)組長(zhǎng)度-1),最終得到存儲(chǔ)在數(shù)組table的位置(即數(shù)組下標(biāo)、索引)
}
Map中添加數(shù)據(jù)
put方法
put(int hash, K key, V value, int bucketIndex):向HashMap添加數(shù)據(jù)(成對(duì)存放 key - value)

流程圖

源碼
/**
* 函數(shù)使用原型
*/
map.put("name", "huangkaiyu");
map.put("age", 21);
public V put(K key, V value)
// 1.如果哈希表未初始化(即 table為空)
if (table == EMPTY_TABLE) {
// 則使用構(gòu)造函數(shù)傳入的閾值(即初始容量) 初始化數(shù)組table
inflateTable(threshold);
}
// 2. 判斷key是否為空值null
// 若key == null,則將該鍵值對(duì)放在table [0](本質(zhì):key = Null時(shí),hash值 = 0,故存放到table[0]中)
if (key == null)
return putForNullKey(value);
//若 key ≠ null,則計(jì)算存放數(shù)組 table 中的位置(下標(biāo)、索引)
//計(jì)算hash值
int hash = hash(key);
//傳入hash值和table長(zhǎng)度算出index
int i = indexFor(hash, table.length);
// 3. 遍歷table[indexFor]對(duì)應(yīng)的鏈表判斷該key對(duì)應(yīng)的值是否已存在
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
//若該key已存在(即 key-value已存在 ),則用替換原來(lái)的值
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue; //并返回舊的value
}
}
//改動(dòng)計(jì)數(shù)器+1
modCount++;
// 若該key不存在,則將“key-value”添加到table中
addEntry(hash, key, value, i);
return null;
}
inflateTable方法
inflateTable(int toSize):初始化數(shù)組(table)、擴(kuò)容閾值(threshold)
注意:
真正初始化哈希表(初始化存儲(chǔ)數(shù)組table)是在第1次添加鍵值對(duì)時(shí),即第1次調(diào)用put()時(shí)
/**
* put中調(diào)用
*/
if (table == EMPTY_TABLE) {
//此處傳入的是構(gòu)造函數(shù)時(shí)設(shè)置的閾值(即初始容量),不是真正的擴(kuò)容閾值
inflateTable(threshold);
}
private void inflateTable(int toSize) {
// 1. 將傳入的容量大小轉(zhuǎn)化為:>傳入容量大小的最小的2的次冪(傳入18轉(zhuǎn)化得32)
int capacity = roundUpToPowerOf2(toSize);
// 2. 重新計(jì)算閾值 threshold = 容量 * 加載因子(之前存的是容量)
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
// 3.傳入容量初始化位桶數(shù)組table(作為數(shù)組長(zhǎng)度)
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}
/**
* roundUpToPowerOf2(toSize)
* 作用:將傳入的容量大小轉(zhuǎn)化為:>傳入容量大小的最小的2的冪
* 特別注意:容量大小必須為2的冪
*/
private static int roundUpToPowerOf2(int number) {
//若超過(guò)了最大值,則設(shè)置為最大值;否則,設(shè)置為大于傳入容量大小的最小的2的次冪
return number >= MAXIMUM_CAPACITY ?
MAXIMUM_CAPACITY : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
putForNullKey方法
putForNullKey(V value):當(dāng) key ==null時(shí),將該 key-value 的存儲(chǔ)位置規(guī)定為數(shù)組table 中的第1個(gè)位置,即table [0]
/**
* put()方法調(diào)用時(shí) 傳入的key為空
*/
if (key == null)
return putForNullKey(value);
/**
* 遍歷以table[0]為首的鏈表,尋找是否存在key==null 對(duì)應(yīng)的鍵值對(duì)
有就替換并返回舊值,沒(méi)有就調(diào)用addEntry()將(null,value)添加到鏈表中
*/
private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
//如果鏈表結(jié)點(diǎn)key為空
if (e.key == null) {
//保存舊值
V oldValue = e.value;
//鏈表賦新值
e.value = value;
e.recordAccess(this);
//返回舊值
return oldValue;
}
}
//改動(dòng)次數(shù)+1
modCount++;
// 若沒(méi)有key==null的鍵,那么調(diào)用addEntry()將其加入鏈表
addEntry(0, null, value, 0);
// a. addEntry()的第1個(gè)參數(shù)hash值傳入0(當(dāng)key = null時(shí),也有hash值 = 0,所以HashMap的key 可為null)
// c. 對(duì)比HashTable,由于HashTable對(duì)key直接hashCode(),若key為null時(shí),會(huì)拋出異常,所以HashTable的key不可為null
// d. 此處只需知道是將 key-value 添加到HashMap中即可,關(guān)于addEntry()的源碼分析將等到下面再詳細(xì)說(shuō)明,
return null;
}
addEntry方法
addEntry(int hash, K key, V value, int bucketIndex):添加鍵值對(duì)(Entry )到 HashMap中
/**
* put中key不存在調(diào)用,將Entry對(duì)象存入鏈表
*/
void addEntry(int hash, K key, V value, int bucketIndex) {
// 1. 插入前先判斷是否需要擴(kuò)容
// 如果元素個(gè)數(shù)>=擴(kuò)容閾值 并且 對(duì)應(yīng)數(shù)組下標(biāo)不為空
if ((size >= threshold) && (null != table[bucketIndex])) {
//擴(kuò)容2倍
resize(2 * table.length);
// 重新計(jì)算Key對(duì)應(yīng)的hash值
hash = (null != key) ? hash(key) : 0;
// 重新計(jì)算該Key對(duì)應(yīng)的hash值的存儲(chǔ)數(shù)組下標(biāo)位置
bucketIndex = indexFor(hash, table.length);
}
//如果不需要擴(kuò)容,則創(chuàng)建1個(gè)新的Entry并放入到數(shù)組中
createEntry(hash, key, value, bucketIndex);
}
createEntry方法
createEntry(int hash, K key, V value, int bucketIndex)
/**
* 分析2:createEntry(hash, key, value, bucketIndex);
* 作用: 若容量足夠,則創(chuàng)建1個(gè)新的數(shù)組元素(Entry) 并放入到數(shù)組中
*/
void createEntry(int hash, K key, V value, int bucketIndex) {
// 1. 把table中該位置原來(lái)的Entry保存
Entry<K,V> e = table[bucketIndex];
// 2. 在table中該位置新建一個(gè)Entry:將原頭結(jié)點(diǎn)位置(數(shù)組上)的鍵值對(duì) 放入到(鏈表)后1個(gè)節(jié)點(diǎn)中、將需插入的鍵值對(duì) 放入到頭結(jié)點(diǎn)中(數(shù)組上)-> 從而形成鏈表
// 即 在插入元素時(shí),是在鏈表頭插入的,table中的每個(gè)位置永遠(yuǎn)只保存最新插入的Entry,舊的Entry則放入到鏈表中(即 解決Hash沖突)
table[bucketIndex] = new Entry<>(hash, key, value, e);
// 3. 哈希表的鍵值對(duì)數(shù)量計(jì)數(shù)增加
size++;
}
擴(kuò)容方法
resize方法
resize(int newCapacity):擴(kuò)容為原來(lái)兩倍
在擴(kuò)容resize()過(guò)程中,在將舊數(shù)組上的數(shù)據(jù) 轉(zhuǎn)移到 新數(shù)組上時(shí),轉(zhuǎn)移操作 = 按舊鏈表的正序遍歷鏈表、在新鏈表的頭部依次插入,即在轉(zhuǎn)移數(shù)據(jù)、擴(kuò)容后,容易出現(xiàn)鏈表逆序的情況
設(shè)重新計(jì)算存儲(chǔ)位置后不變,即擴(kuò)容前 = 1->2->3,擴(kuò)容后 = 3->2->1
此時(shí)若(多線程)并發(fā)執(zhí)行 put()操作,一旦出現(xiàn)擴(kuò)容情況,則 容易出現(xiàn) 環(huán)形鏈表,從而在獲取數(shù)據(jù)、遍歷鏈表時(shí) 形成死循環(huán)(Infinite Loop),即 死鎖的狀態(tài) = 線程不安全
/**
* resize(2 * table.length)
* 作用:當(dāng)容量不足時(shí)(容量 > 閾值),則擴(kuò)容(擴(kuò)到2倍)
*/
void resize(int newCapacity) {
// 1. 保存舊數(shù)組(old table)
Entry[] oldTable = table;
// 2. 保存舊容量(數(shù)組長(zhǎng)度)
int oldCapacity = oldTable.length;
// 3. 若舊容量已經(jīng)是系統(tǒng)默認(rèn)最大容量了,那么將擴(kuò)容閾值設(shè)置成整型的最大值,退出
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
// 4. 根據(jù)新容量(2倍容量)新建1個(gè)數(shù)組,即新table
Entry[] newTable = new Entry[newCapacity];
// 5. 將舊數(shù)組上的數(shù)據(jù)(鍵值對(duì))轉(zhuǎn)移到新table中,從而完成擴(kuò)容
transfer(newTable);
// 6. 新數(shù)組table引用到HashMap的table屬性上
table = newTable;
// 7. 重新設(shè)置閾值
threshold = (int)(newCapacity * loadFactor);
}
transfer方法
transfer(Entry[] newTable):
/**
* transfer(newTable);
* 作用:將舊數(shù)組上的數(shù)據(jù)(鍵值對(duì))轉(zhuǎn)移到新table中,從而完成擴(kuò)容
* 過(guò)程:按舊鏈表的正序遍歷鏈表采用頭插法插入新鏈表
*/
void transfer(Entry[] newTable) {
// 1. src指向原table
Entry[] src = table;
// 2. 獲取新數(shù)組的大小
int newCapacity = newTable.length;
// 3. 通過(guò)遍歷舊table,將鍵值對(duì)轉(zhuǎn)移到新table上
for (int j = 0; j < src.length; j++) {
// 創(chuàng)建輔助entry指向舊數(shù)組中的元素
Entry<K,V> e = src[j];
if (e != null) {
// 釋放舊數(shù)組的對(duì)象引用(for循環(huán)后,舊數(shù)組不再引用任何對(duì)象)
src[j] = null;
//開(kāi)始遍歷
do {
//創(chuàng)建輔助指針next(因是單鏈表,故要保存下1個(gè)結(jié)點(diǎn),否則轉(zhuǎn)移后鏈表會(huì)斷開(kāi) )
Entry<K,V> next = e.next;
// 重新計(jì)算每個(gè)元素的存儲(chǔ)位置
int i = indexFor(e.hash, newCapacity);
//頭插法插入
e.next = newTable[i];
newTable[i] = e;
// e跳到下一個(gè)entry
e = next;
} while (e != null);
// 循環(huán)直到遍歷完數(shù)組上的所有數(shù)據(jù)元素
}
}
}
從HashMap中獲取數(shù)據(jù)
get方法
public V get(Object key):根據(jù)鍵key,向HashMap獲取對(duì)應(yīng)的值
public V get(Object key) {
// 1. 當(dāng)key == null時(shí),則到table[0]為頭結(jié)點(diǎn)的鏈表去檢索
if (key == null)
return getForNullKey();
// 2. 當(dāng)key ≠ null時(shí),去獲得對(duì)應(yīng)值
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
/**
* getForNullKey()
* 作用:當(dāng)key == null時(shí),在table[0]中去尋找對(duì)應(yīng) key為null的鍵值對(duì)
*/
private V getForNullKey() {
if (size == 0) {
return null;
}
// 遍歷以table[0]為頭結(jié)點(diǎn)的鏈表,尋找 key==null 對(duì)應(yīng)的值
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
// 從table[0]中取key==null的value值
if (e.key == null)
return e.value;
}
return null;
}
/**
* getEntry(key)
* 作用:當(dāng)key ≠ null時(shí),去獲得對(duì)應(yīng)值
*/
final Entry<K,V> getEntry(Object key) {
//如果元素個(gè)數(shù)為空返回null
if (size == 0) {
return null;
}
// 1. 計(jì)算key對(duì)應(yīng)的hash值
int hash = (key == null) ? 0 : hash(key);
// 2. 根據(jù)hash值計(jì)算出對(duì)應(yīng)的數(shù)組下標(biāo)
// 3. 遍歷對(duì)應(yīng)index的數(shù)組元素為頭結(jié)點(diǎn)的鏈表,檢索鍵值對(duì)
for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
Object k;
// 若 hash值 & key 相等,則證明該Entry = 我們要的鍵值對(duì)
// 通過(guò)==或者equals()判斷key是否相等
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
從HashMap中刪除數(shù)據(jù)
remove方法
remove(Object key):刪除該鍵值對(duì)
public V remove(Object key) {
Entry<K,V> e = removeEntryForKey(key);
return (e == null ? null : e.value);
}
final Entry<K,V> removeEntryForKey(Object key) {
if (size == 0) {
return null;
}
// 1. 計(jì)算hash值
int hash = (key == null) ? 0 : hash(key);
// 2. 計(jì)算存儲(chǔ)的數(shù)組下標(biāo)位置
int i = indexFor(hash, table.length);
//prev記錄要?jiǎng)h除entry的前一個(gè)entry
Entry<K,V> prev = table[i];
//e記錄要?jiǎng)h除的entry
Entry<K,V> e = prev;
while (e != null) {
//輔助指針,指向下一個(gè)entry
Entry<K,V> next = e.next;
Object k;
//如果key相等
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
modCount++; //改動(dòng)次數(shù)+1
size--; //元素個(gè)數(shù)-1
// 若刪除的是鏈表的頭結(jié)點(diǎn)
if (prev == e)
// 則將頭結(jié)點(diǎn)的next引用存入table[i]中
table[i] = next;
//否則 將當(dāng)前結(jié)點(diǎn)的前1個(gè)結(jié)點(diǎn)中的next指向當(dāng)前結(jié)點(diǎn)的下一個(gè)結(jié)點(diǎn)(直接越過(guò)當(dāng)前Entry)
else
prev.next = next;
e.recordRemoval(this);
return e;
}
//prev指向當(dāng)前結(jié)點(diǎn)
prev = e;
//e指向下一個(gè)結(jié)點(diǎn)
e = next;
}
//遍歷結(jié)束e為null,表示沒(méi)找到返回null
return e;
}
對(duì)HashMap的其他操作
HashMap除了核心的put()、get()函數(shù),還有以下主要使用的函數(shù)方法
| void clear(); | 清除哈希表中的所有鍵值對(duì) |
|---|---|
| int size(); | 返回哈希表中所有 鍵值對(duì)的數(shù)量 = 數(shù)組中的鍵值對(duì) + 鏈表中的鍵值對(duì) |
| boolean isEmpty(); | 判斷HashMap是否為空;size == 0時(shí) 表示為 空 |
| void putAll(Map<? extends K, ? extends V> m); | 將指定Map中的鍵值對(duì) 復(fù)制到 此Map中 |
| boolean containsKey(Object key); | 判斷是否存在該鍵的鍵值對(duì);是 則返回true |
| boolean containsValue(Object value); | 判斷是否存在該值的鍵值對(duì);是 則返回true |
源碼
/**
* 函數(shù):isEmpty()
* 作用:判斷HashMap是否為空,即無(wú)鍵值對(duì);size == 0時(shí) 表示為 空
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 函數(shù):size()
* 作用:返回哈希表中所有 鍵值對(duì)的數(shù)量 = 數(shù)組中的鍵值對(duì) + 鏈表中的鍵值對(duì)
*/
public int size() {
return size;
}
/**
* 函數(shù):clear()
* 作用:清空哈希表,即刪除所有鍵值對(duì)
* 原理:將數(shù)組table中存儲(chǔ)的Entry全部置為null、size置為0
*/
public void clear() {
//改動(dòng)次數(shù)+1
modCount++;
//全部元素設(shè)空
Arrays.fill(table, null);
//元素個(gè)數(shù)清0
size = 0;
}
/**
* 函數(shù):putAll(Map<? extends K, ? extends V> m)
* 作用:將指定Map中的鍵值對(duì) 復(fù)制到 此Map中
* 原理:類(lèi)似Put函數(shù)
*/
public void putAll(Map<? extends K, ? extends V> m) {
// 1. 統(tǒng)計(jì)需復(fù)制多少個(gè)鍵值對(duì)
int numKeysToBeAdded = m.size();
if (numKeysToBeAdded == 0)
return;
// 2. 若table還沒(méi)初始化,先用剛剛統(tǒng)計(jì)的復(fù)制數(shù)去初始化table
if (table == EMPTY_TABLE) {
inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
}
// 3. 若需復(fù)制的數(shù)目 > 閾值,則需先擴(kuò)容
if (numKeysToBeAdded > threshold) {
int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
if (targetCapacity > MAXIMUM_CAPACITY)
targetCapacity = MAXIMUM_CAPACITY;
int newCapacity = table.length;
while (newCapacity < targetCapacity)
newCapacity <<= 1;
if (newCapacity > table.length)
resize(newCapacity);
}
// 4. 開(kāi)始復(fù)制(實(shí)際上不斷調(diào)用Put函數(shù)插入)
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
put(e.getKey(), e.getValue());
}
/**
* 函數(shù):containsKey(Object key)
* 作用:判斷是否存在該鍵的鍵值對(duì);是 則返回true
* 原理:調(diào)用get(),判斷是否為Null
*/
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
/**
* 函數(shù):containsValue(Object value)
* 作用:判斷是否存在該值的鍵值對(duì);是 則返回true
*/
public boolean containsValue(Object value) {
// 若value為空,則調(diào)用containsNullValue()
if (value == null)
return containsNullValue();
// 若value不為空,則遍歷鏈表中的每個(gè)Entry,通過(guò)equals()比較values 判斷是否存在
Entry[] tab = table;
for (int i = 0; i < tab.length ; i++)
for (Entry e = tab[i] ; e != null ; e = e.next)
if (value.equals(e.value))
return true;//返回true
return false;
}
// 判斷是否有空值
private boolean containsNullValue() {
Entry[] tab = table;
for (int i = 0; i < tab.length ; i++)
for (Entry e = tab[i] ; e != null ; e = e.next)
if (e.value == null)
return true;
return false;
}
1.7和1.8版本區(qū)別
JDK 1.8 的優(yōu)化目的主要是:減少 Hash沖突 & 提高哈希表的存、取效率
數(shù)據(jù)結(jié)構(gòu)
| 版本 | 存儲(chǔ)結(jié)構(gòu) | 數(shù)組&鏈表結(jié)點(diǎn)實(shí)現(xiàn)類(lèi) | 紅黑樹(shù)的實(shí)現(xiàn)類(lèi) | 初始化方式 |
|---|---|---|---|---|
| JDK1.7 | 數(shù)組+鏈表 | Entry類(lèi) | 無(wú)紅黑樹(shù) | 單獨(dú)函數(shù):inflateTable() |
| JDK1.8 | 數(shù)組+鏈表+紅黑樹(shù) | Node類(lèi) | TreeNode類(lèi) | 直接集成在擴(kuò)容函數(shù):resize()中 |
hash值計(jì)算方式
| 版本 | hash值計(jì)算方式 |
|---|---|
| JDK1.7 | 1.hashcode計(jì)算 |
| JDK1.8 | 按照擴(kuò)容后的規(guī)律計(jì)算(擴(kuò)容后的位置=原位置 or 原位置 +舊容量) |
擴(kuò)容機(jī)制
| 版本 | 重hash計(jì)算位置 |
|---|---|
| JDK1.7 | 1.Object.hashCode計(jì)算 2. 9次擾動(dòng)處理 =4次位運(yùn)算+5次異或運(yùn)算 |
| JDK1.8 | 1.Object.hashCode計(jì)算 2. 2次擾動(dòng)處理 =1次位運(yùn)算+1次異或運(yùn)算 |
到此這篇關(guān)于Java1.7全網(wǎng)最深入HashMap源碼解析的文章就介紹到這了,更多相關(guān)Java HashMap 源碼解析內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springMVC前臺(tái)傳數(shù)組類(lèi)型,后臺(tái)用list類(lèi)型接收實(shí)例代碼
這篇文章主要介紹了springMVC前臺(tái)傳數(shù)組類(lèi)型,后臺(tái)用list類(lèi)型接收實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12
詳解Java的MyBatis框架中SQL語(yǔ)句映射部分的編寫(xiě)
這篇文章主要介紹了Java的MyBatis框架中SQL語(yǔ)句映射部分的編寫(xiě),文中分為resultMap和增刪查改實(shí)現(xiàn)兩個(gè)部分來(lái)講解,需要的朋友可以參考下2016-04-04
SpringBoot整合SpringSecurity實(shí)現(xiàn)認(rèn)證攔截的教程
我們寫(xiě)的任何一個(gè)項(xiàng)目,都應(yīng)該有安全防護(hù),不應(yīng)該讓這個(gè)項(xiàng)目進(jìn)行“裸奔”,否則很容易被別人進(jìn)行攻擊。而在SpringBoot環(huán)境中,其實(shí)可以很容易實(shí)現(xiàn)安全保護(hù),本文給大家介紹SpringBoot如何整合SpringSecurity實(shí)現(xiàn)認(rèn)證攔截,需要的朋友可以參考下2023-05-05
JAVA調(diào)用SAP WEBSERVICE服務(wù)實(shí)現(xiàn)流程圖解
這篇文章主要介紹了JAVA調(diào)用SAP WEBSERVICE服務(wù)實(shí)現(xiàn)流程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
java基于包結(jié)構(gòu)的請(qǐng)求路由實(shí)現(xiàn)實(shí)例分享
基于包結(jié)構(gòu)的請(qǐng)求路由簡(jiǎn)單實(shí)現(xiàn)實(shí)例分享,大家參考使用吧2013-12-12
使用java數(shù)組 封裝自己的數(shù)組操作示例
這篇文章主要介紹了使用java數(shù)組 封裝自己的數(shù)組操作,結(jié)合實(shí)例形式分析了java數(shù)組索引、遍歷等相關(guān)封裝操作技巧與注意事項(xiàng),需要的朋友可以參考下2020-03-03

