一、HashMap的成員變量
int DEFAULT_INITIAL_CAPACITY = 16:默認的初始容量爲16
int MAXIMUM_CAPACITY = 1 << 30:最大的容量爲 2 ^ 30
float DEFAULT_LOAD_FACTOR = 0.75f:默認的加載因子爲 0.75f
Entry< K,V>[] table:Entry類型的數組,HashMap用這個來維護內部的數據結構,它的長度由容量決定
int size:HashMap的大小
int threshold:HashMap的極限容量,擴容臨界點(容量和加載因子的乘積)
加載因子
1. 加載因子是哈希表在元素增加之前可以達到多滿的一種尺度,相當於一個閾值。當元素的個數達到閾值時,就會進行擴容。它衡量的是一個散列表的空間的使用程度,負載因子越大表示散列表的裝填程度越高,反之愈小。
2. 對於使用鏈表法的散列表來說,查找一個元素的平均時間是O(1+a),加載因子是表示Hsah表中元素的填滿的程度.若加載因子越大,填滿的元素越多,好處是,空間利用率高了,但衝突的機會加大了.反之,加載因子越小,填滿的元素越少,好處是衝突的機會減小了,但空間浪費多了.衝突的機會越大,則查找的成本越高.反之,查找的成本越小
3. 因而,查找時間就越小,因此,必須在”衝突的機會”與”空間利用率”之間尋找一種平衡與折衷. 這種平衡與折衷本質上是數據結構中有名的”時-空”矛盾的平衡與折衷.
4.系統默認負載因子爲0.75,一般情況下我們是無需修改的。
5.當哈希表中的數量超出了加載因子與當前容量的乘積時,則要對該哈希表進行 rehash 操作(即重建內部數據結構),從而哈希表將具有大約兩倍的桶數。
二、HashMap的數據結構
我們知道在Java中最常用的兩種結構是數組和模擬指針(引用),幾乎所有的數據結構都可以利用這兩種來組合實現,HashMap也是如此。實際上HashMap是一個“鏈表散列”,如下是它數據結構:
從上圖我們可以看出HashMap底層實現還是數組,只是數組的每一項都是一條鏈。其中參數initialCapacity就代表了該數組的長度。下面爲HashMap構造函數的源碼:
//無參構造器
public HashMap() {
//默認初始容量大小爲16,默認的加載因子爲0.75f
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity, float loadFactor) {
//初始容量不能小於0
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//初始容量不能超過1073741824
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//加載因子不能小於等於0,或者加載因子不能是非數字
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
//設置加載因子
this.loadFactor = loadFactor;
//設置臨界值
threshold = initialCapacity;
//僞構造,裏面沒有代碼
init();
}
put()方法代碼
public V put(K key, V value) {
//先判斷哈希表是否爲空,第一次put的話肯定是爲空的,
if (table == EMPTY_TABLE) {
// roundUpToPowerOf2方法的作用是將構造器傳入的容量初始化大小
//轉成最接近2的n字方值,爲什麼要2的n字方,下面會提到
int capacity = roundUpToPowerOf2(threshold);
//臨界值是加載因子*容量大小
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
//創建一個Entry數組
table = new Entry[capacity];
//initHashSeedAsNeeded方法的作用:找到與該實例的一個哈希掩碼值,使哈希碰撞機率更爲小.裏
//面會生成一個hashSeed,將會在生成哈希值裏面可能會用到。
initHashSeedAsNeeded(capacity);
}
//如果key爲null
if (key == null)
//這個方法下面講解
return putForNullKey(value);
//計算key的哈希值
int hash = hash(key);
//計算該哈希值在哈希表的下標
int i = indexFor(hash, table.length);
//如果剛剛計算出來的下標在哈希表裏面爲空的話,將不會進入循環
//不爲空將遍歷table[i]的鏈表
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
//判斷該鏈表上是否有相同的哈希值和相同的地址值,或者key相同
//若存在則覆蓋舊值,返回舊值
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
//這個方法下面講解
addEntry(hash, key, value, i);
return null;
}
1.爲什麼容量大小要爲2的n次方,請點擊
2. 如果爲null,則調用putForNullKey:這就是爲什麼HashMap可以用null作爲鍵的原因,來看看HashMap是如何處理null鍵的:
private V putForNullKey(V value) {
//查找哈希表中0索引的位置,是否不爲空,如果不爲空,則遍歷0索引的鏈表
//查找key==null的鍵值,覆蓋並返回舊值。
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
//將null的鍵放入哈希表0索引的位置
addEntry(0, null, value, 0);
return null;
}
3.添加新結點的方法
void addEntry(int hash, K key, V value, int bucketIndex) {
//如果結點個數大於或等於臨界值和該哈希表指定的索引位置不爲null
if ((size >= threshold) && (null != table[bucketIndex])) {
//擴容會在重點講解
resize(2 * table.length);
//這一步就是對null的處理,如果key爲null,hash值爲0,
//也就是會插入到哈希表的表頭table[0]的位置
hash = (null != key) ? hash(key) : 0;
//因爲擴容了,需要重新計算哈希表的位置
bucketIndex = indexFor(hash, table.length);
}
//創建Entry結點的操作
createEntry(hash, key, value, bucketIndex);
}
void createEntry(int hash, K key, V value, int bucketIndex) {
//查找出指定索引的結點對象,目的:形成一個鏈表
Entry<K,V> e = table[bucketIndex];
//第一個參數書哈希值,第二個是key值,第三個是value值
//第四個哈希表指定索引結點的對象,這樣就形成了一個單鏈鏈表了。
//爲什麼要放在鏈表頭,因爲好像作者說後面放進去的結點會更大機率使用到。歡迎糾錯。
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
int hash;
/**
* Creates new entry.
*/
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
5.擴容
void resize(int newCapacity) {
//引用擴容前的Entry數組
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
//如果擴容前的數組大小如果已經達到最大(2^30)了
//修改閾值爲int的最大值(2^31-1),這樣以後就不會擴容了
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
//創建一個新的哈希表
Entry[] newTable = new Entry[newCapacity];
//將當前所有的哈希表數據複製到新的哈希表
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
//計算臨界值
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
//將當前所有的哈希表數據複製到新的哈希表
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
//遍歷舊的哈希表
for (Entry<K,V> e : table) {
while(null != e) {
//保存舊的哈希表對應的鏈表頭的下一個結點
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
//因爲哈希表的長度變了,需要重新計算索引
int i = indexFor(e.hash, newCapacity);
//第一次循環的newTable[i]爲空,賦值給當前結點的下一個元素,
//下面有圖會講解這句代碼的含義
e.next = newTable[i];
//將結點賦值到新的哈希表
newTable[i] = e;
e = next;
}
}
}
get方法
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
//key爲null的處理方法
private V getForNullKey() {
if (size == 0) {
return null;
}
//因爲key爲null添加的時候是放在哈希表索引0的位置的。
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
//找到key爲null,則終止循環,返回值
if (e.key == null)
return e.value;
}
return null;
}
//獲取值
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
//計算key的哈希值
int hash = (key == null) ? 0 : hash(key);
//table[indexFor(hash, table.length)這個方法的目的是找到對應的鏈表,開始遍歷
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
remove方法
final Entry<K,V> removeEntryForKey(Object key) {
if (size == 0) {
return null;
}
int hash = (key == null) ? 0 : hash(key);
int i = indexFor(hash, table.length);
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;
}
迭代器
private abstract class HashIterator<E> implements Iterator<E> {
Entry<K,V> next; // next entry to return
int expectedModCount; // For fast-fail
int index; // 記錄索引
Entry<K,V> current; // current entry
HashIterator() {
expectedModCount = modCount;
if (size > 0) { // advance to first entry
Entry[] t = table;
//找到在數組裏第一個元素
while (index < t.length && (next = t[index++]) == null)
;
}
}
public final boolean hasNext() {
return next != null;
}
final Entry<K,V> nextEntry() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Entry<K,V> e = next;
if (e == null)
throw new NoSuchElementException();
//如果在這個索引上沒有單向鏈表的話,
if ((next = e.next) == null) {
Entry[] t = table;
//向下個索引查找不爲null的元素
while (index < t.length && (next = t[index++]) == null)
;
}
current = e;
return e;
}
public void remove() {
if (current == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Object k = current.key;
current = null;
HashMap.this.removeEntryForKey(k);
expectedModCount = modCount;
}
}
參考文章
https://blog.csdn.net/jeffleo/article/details/54946424
https://blog.csdn.net/qq_27093465/article/details/52270519