一、基本圖示
二、基本介紹
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
結構
- HashMap 繼承了 AbstractMap 類
- HashMap 實現了 Map 接口
- HashMap 實現了 Cloneable 類,覆蓋了 clone 方法,可以被克隆
- 實現了 Serializable 接口,支持序列化
特性
- 底層是使用了拉鍊法的散列表,Entry<k,v>[]
- 元素是無序的,即遍歷得到元素的順序和放進去的元素的順序不同
- 是線程不安全的
- key 和 value 都允許爲 null
- 1 個 key 只能對應 1 個 value,1 個 value 對應多個 key
三、基本參數
// 初始容量爲 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 初始加載因子爲 0.75f
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 空的哈希表
static final Entry<?,?>[] EMPTY_TABLE = {};
// 實際使用的哈希表
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
// 閥值,用來規定什麼時候擴容,閥值=當前數組長度 * 負載因子
int threshold;
HashMap 使用以 Entry 爲單位的單向鏈表存儲數據,用來存儲 key,value,hash 和 下一個 Entry 的指向
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
int hash;
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
...
}
四、構造函數
// 如果沒有傳入任何參數,則初始容量爲 16,默認負載因子爲 0.75f
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
// 一個參數的構造函數,用戶可以自己設置初始容量
public HashMap(int initialCapacity) {
// 調用具有兩個參數的構造函數,此時還是傳入默認負載因子
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
// 用戶可以自己設定初始變量和負載因子
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;
// 閥值設置爲傳入的容量
threshold = initialCapacity;
init();
}
五、添加方法
public V put(K key, V value) {
// 1.如果哈希表一開始是空的
if (table == EMPTY_TABLE) {
// 爲哈希表分配存儲空間,默認傳入的 threshold 爲 16
inflateTable(threshold);
}
// 2.如果傳入的鍵爲 null,則直接返回
if (key == null)
return putForNullKey(value);
// 3.如果傳入的鍵不爲 null,則根據傳入的 key 值計算 hash 值
int hash = hash(key);
// 4.根據 hash 值和當前數組的長度計算在數組中的索引
int i = indexFor(hash, table.length);
// 5.如果這個這個索引所在的位置已經有元素了,就以這個索引的鏈表頭爲起點開始遍歷以這個位置爲頭節點的鏈表
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
// 如果對應的鍵、值都相等
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
// oldValue 保存舊的值
V oldValue = e.value;
// 將新的值賦給舊的值
e.value = value;
e.recordAccess(this);
// 返回舊的值
return oldValue;
}
}
modCount++;
// 6.如果沒有對應的 key 就添加 Entry 到 HashMap 中
addEntry(hash, key, value, i);
return null;
}
①. 首先判斷哈希表是否爲空,如果爲空,則調用 inflateTable 函數對哈希表進行初始化。如果傳入的值可能不是 2 的冪次方,則需要轉化成 ≥ 初始值的最小的 2 次冪,然後對哈希表進行初始化。經過 inflateTable 方法之後的哈希表的長度都是 2 的冪,即 2^n
對於 roudUpPowerOf2 方法,如果傳入的 toSize=10,則 capacity = 16,toSize = 16,capacity = 16,toSize = 17,capacity = 32…
private void inflateTable(int toSize) {
// 通過roundUpToPowerOf2(toSize)可以確保capacity爲大於或等於toSize的最接近toSize的二次冪
int capacity = roundUpToPowerOf2(toSize);
// 這裏設置閥值 = capacity * loadFactor
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
// 初始化哈希表,容量就是 capacity
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}
②. 如果傳入的 key 爲 null,則返回 putForNullKey 方法,該方法會將 key 爲 null 對應的元素永遠放在 table[0] 位置,無論有沒有發生哈希碰撞。如果 table[0] 所在的單鏈表已經有 key 爲 null 的元素了,則新插入的會替換舊的 key 爲 null 的元素
// 將 key 爲 null 的鍵值對傳入 table[0]
private V putForNullKey(V value) {
// 遍歷 table[0] 的單鏈表
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
// 如果 table[0] 上已經有 key 爲 null 的元素,則進行替換
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
// 如果 table[0] 上沒有 key 爲 null 的值
addEntry(0, null, value, 0);
return null;
}
通過一個圖片可以更加直觀的看到整個過程,第一次因爲 table[0] 沒有 key 爲 null 的元素,就會插入到頭部,第二次因爲 table[0] 已經有 key 爲 null 的元素了,便會直接覆蓋
PS:在 hashmap 擴容之前的情況,此時 key 爲 null 的 Entry 會一直在 table[0] 的第一個位置;而在擴容之後,可能會鏈表逆置,就不是上面那種情況了,但是,一定還是在 table[0] 的位置,只是不一定是第一個
③. 如果哈希表既不爲空,key 也不爲 null,則調用 hash 方法計算傳入的 key 的 hash 值
inal int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
④. 根據計算出來的 hash 值和當前哈希表的長度來計算當前 key 在哈希表中的位置 i,此時哈希表的長度 length 都是 2 的冪
static int indexFor(int h, int length) {
return h & (length-1);
}
⑤. 遍歷以 table[i] 爲頭節點的單鏈表,如果傳入的值的 hash 值和 key 值和鏈表裏面已經存在的值的 hash 值和 key 值相等,則用新的 Entry 的 value 覆蓋原來節點的 value
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
// 如果對應的鍵、值都相等
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
// oldValue 保存舊的值
V oldValue = e.value;
// 將新的值賦給舊的值
e.value = value;
e.recordAccess(this);
// 返回舊的值
return oldValue;
}
}
⑥. 接下來便會調用 addEntry 方法,擴容和創建鍵值對的方法都和它有關,如果遇到下面這兩種情況,則會來調用這個方法
- 哈希表的位置 i 沒有元素
- 哈希表的位置 i 存在元素,但是要添加的元素的 hash 值或者 key 值與位置 i 的鏈表中的元素的這兩個數值不等
該方法會先根據閥值大小判斷是否需要進行擴容,如果需要則先擴容,擴容的時候還需要重新移動元素。等這一切都做完後,重複之前的步驟
- 計算要添加的元素的 hash 值
- 計算要添加的元素在新數組中的位置
void addEntry(int hash, K key, V value, int bucketIndex) {
// 如果鍵值對的數量大於等於閥值並且哈希表中對應的位置不爲 null
if ((size >= threshold) && (null != table[bucketIndex])) {
// 將哈希表擴容爲原來的 2 倍
resize(2 * table.length);
// 判斷傳入的 key 是否爲空,不爲空則再次調用 hash 方法計算 hash 值
hash = (null != key) ? hash(key) : 0;
// 根據新表的長度重新計算所放的位置
bucketIndex = indexFor(hash, table.length);
}
// 無論是否需要擴容,都需要創建新的節點,添加到指定位置
createEntry(hash, key, value, bucketIndex);
}
數組擴容的方法,其實就是創建一個新的 Entry 數組,用新的容量初始化,然後重新計算元素在 Entry 數組中的位置,即 hash 值
void resize(int newCapacity) {
// 獲取舊的 table 數組
Entry[] oldTable = table;
// 獲取舊的數組的長度
int oldCapacity = oldTable.length;
// 極端情況,如果舊的長度已經是最大容量
if (oldCapacity == MAXIMUM_CAPACITY) {
// 直接等於最大容量
threshold = Integer.MAX_VALUE;
return;
}
// 1.初始化一個新的 Entry 數組,傳入的參數是舊的數組的兩倍
Entry[] newTable = new Entry[newCapacity];
// 2.將鍵值對轉移到新的 Entry 數組
transfer(newTable, initHashSeedAsNeeded(newCapacity));
// 3.將新的數組賦值給舊的數組
table = newTable;
// 4.重新計算閥值
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
其中最關鍵的就是轉移元素的方法 transfer,其實移動的時候也是考慮兩種情況
- 所在的 table[i] 至少是長度 ≥ 2 的單鏈表,此時如果轉移後依然還在同一個位置,則需要將以前的鏈表逆置
- 所在的 table[i] 只有一個元素,則直接根據新的位置轉移到新的數組
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
// 遍歷哈希表 table
for (Entry<K,V> e : table) {
while(null != e) {
// next 用來保存頭節點的下一個節點
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
// 計算在元素在新的哈希表中的位置
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
通過畫圖可以更加清楚的看到整個元素轉移的過程,當然,這只是最極端的一種情況,即原來單鏈表上的元素轉移到新的數組,依然還是同一個單鏈表。可以看到,經過轉移之後,會將原來單鏈表的元素進行逆置,即和原來的順序是完全相反的
擴容完了之後,需要創建節點並且添加到哈希表中去。需要分兩種情況
- 如果沒有發生哈希碰撞,則直接添加到對應的數組中,此時該位置只要這一個元素
- 如果發生哈希碰撞,則需要添加到對應元素的前面
// 創建 Entry 鍵值對,該鍵值對包括 key,value 已經指向的位置 next
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
// 初始化 next 的指向
next = n;
key = k;
hash = h;
}
照樣看個圖,如果發生哈希碰撞,則新元素傳到之前元素的前面。這裏因爲 Entry 的構造函數的最後一個參數就是指向下一個節點的引用 next,而傳入的 e 就是當前已經存在的節點,因此新傳入節點的 next 就是當前的 e
六、刪除方法
刪除元素也是根據 key 值來找到對應位置,然後遍歷和判斷進行刪除的
public V remove(Object key) {
Entry<K,V> e = removeEntryForKey(key);
return (e == null ? null : e.value);
}
// 根據 key 值找到要刪除的 Entry 鍵值對
final Entry<K,V> removeEntryForKey(Object key) {
if (size == 0) {
return null;
}
// 1.根據 key 得到對應的 hash 值
int hash = (key == null) ? 0 : hash(key);
// 2.根據 hash 值和數組長度獲得在數組中的位置 i
int i = indexFor(hash, table.length);
// 3.
Entry<K,V> prev = table[i];
Entry<K,V> e = prev;
while (e != null) {
Entry<K,V> next = e.next;
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
modCount++;
size--;
if (prev == e)
table[i] = next;
else
prev.next = next;
e.recordRemoval(this);
return e;
}
prev = e;
e = next;
}
return e;
}
刪除元素需要考慮兩種情況,即該元素在鏈表第一個,還是在第一個元素後面的位置
1.
如果是第一個位置,則 prev 和 e 同時指向一個 Entry 鍵值對,然後會直接跳過第一個元素,直接指向第 2 個元素,用一個圖示來看一下
2.
如果是 ≥1 的位置,e 指向要刪除的元素,prev 指向 e 的前一個元素,next 指向 e 的後一個元素,最後 prev 跳過 e 直接指向 next 引用。用一個圖示來看一下
七、獲取方法
HashMap 的 get 方法是根據 key 值來獲取 value,需要考慮兩種情況
- 獲取的 key 爲 null
- 獲取的 key 不爲 null
// 根據 key 值獲取 value 的方法
public V get(Object key) {
// 如果傳入的 key 值爲 null
if (key == null)
// 則有特殊的獲取方法
return getForNullKey();
// 如果 key 值不爲 null,先得到該鍵值對
Entry<K,V> entry = getEntry(key);
// 如果沒有找到對應鍵值對,返回 null,否則返回 key 對應的 value
return null == entry ? null : entry.getValue();
}
如果獲取的 key 爲 null,則直接遍歷 table[0] 的鍵值對
// 獲取 key 爲 null 的方法
private V getForNullKey() {
if (size == 0) {
return null;
}
// 因爲 key 爲 null 的鍵值對只可能在 table[0],直接遍歷 table[0]
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
// 只要遍歷到 key 爲 null 的鍵值對,就返回這個鍵值對的 value
if (e.key == null)
return e.value;
}
return null;
}
如果 key 值不爲 null,先得到對應的鍵值對 Entry
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
// 獲取傳入 key 的 hash 值
int hash = (key == null) ? 0 : hash(key);
// 根據 hash 值和當前哈希數組的長度計算鍵值對在數組中的位置
// 遍歷該位置對應的鏈表
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
// 如果 hash 值和 key 值都相等,返回該鍵值對 e
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
// 沒有則返回 null
return null;
}
八、參考
https://mp.weixin.qq.com/s/2paXbnkZBPNs-LwZuDzm5g
http://www.cnblogs.com/skywang12345/p/3310835.html#h4
https://blog.csdn.net/u011240877/article/details/53351188#6hashmap-的獲取方法-get
https://blog.csdn.net/fan2012huan/article/details/51088211#comments
https://blog.csdn.net/ghsau/article/details/16843543