整體介紹
HashMap 是一個采用哈希表實現的鍵值對集合,繼承自AbstractMap,實現了 Map 接口。
-
操作時間
- HashMap的基本操作(
get put
)只需要常量時間和少量的對比操作。時間復雜度為O(n)。 - HashMap迭代操作耗費時間與 HashMap的桶和HashMap內的鍵值對數量成正比
- HashMap的基本操作(
HashMap本身并不是線程同步的,使用了fail-fast機制,但不可靠。
想要同步可以用Map m = Collections.synchronizedMap(new HashMap(...))
-
HashMap內的元素數量一旦達到某個閾值,就會觸發桶擴充,擴大HashMap桶的數量,減小哈希沖突
- 閾值過大,HashMap內的哈希沖突嚴重,查找效率低
- 閾值過小,HashMap的rehashed(桶擴充)頻繁,性能下降
-
放入HashMap的元素需要覆蓋
hashCode()
和equals()
方法。-
hashCode()
決定了對象會放在哪個桶里 -
equals()
決定了在桶的鏈表中如何找到對應的對象
-
-
HashMap采用的是沖突鏈表方式解決哈希沖突問題
image.png
源碼分析
鍵值對結構
HashMap的鍵值對的結構和單鏈表節點差不多,下面只列出了成員變量,沒有列方法。
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
//下一個鍵值對
Entry<K,V> next;
//哈希值
int hash;
}
成員變量
//默認的初始桶數量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大桶數量
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默認的負載因子
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 默認的空HashMap
*/
static final Entry<?,?>[] EMPTY_TABLE = {};
/**
* HashMap的底層實現,初始化為EMPTY_TABLE
*/
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
/**
* 鍵值對數量
*/
transient int size;
// 閾值,除了第一次初始化為DEFAULT_INITIAL_CAPACITY = 16,
// 其余為loadFactor*capacity(當前容量)
int threshold;
//負載因子,和rehash的閾值有關,默認的負載因子為0.75
final float loadFactor;
//這個變量記錄HashMap增減鍵值對的次數,用于實現fail-fast機制
transient int modCount;
/**
*用于替代哈希值(和原哈希值做運算,作為新的哈希值,使哈希沖突更少),
*默認值為0(即不使用這項功能.)
*/
transient int hashSeed = 0;
hash()
這個方法就是上面 hashSeed
替代哈希的方法. 當hashSeed
為0是,返回的值等于k的哈希值.下面的方法多處有用到,這里提一下.
final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
indexFor()
這個方法用于根據哈希值獲取相應的桶的下標.
因為length即桶的數量為2的整數冪,所以
h & (length-1)
就相當于對 length 取模(使用減法替代取模,提升計算效率)-
為了使不同 hash 值發生碰撞的概率更小,盡可能促使元素在哈希表中均勻地散列。
- length為2的整數冪,即為偶數,所以length-1的位數為1,那么
h & (length-1)
就可能是奇數或偶數. - 若length為奇數,那么length-1的位數為0,那么
h & (length-1)
就只能是偶數,有一半的桶被浪費了.
- length為2的整數冪,即為偶數,所以length-1的位數為1,那么
static int indexFor(int h, int length) {
return h & (length-1);
}
get(Object)
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
從這個方法可以看到根據key是否為null,分別調用了getEntry
和getForNullKey
.
-
getForNullKey
- 從這個方法可以看出HashMap可存入{null,X}的鍵值對,而且key==null的哈希值為0.
private V getForNullKey() {
if (size == 0) {
return null;
}
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}
-
getEntry
方法實現很簡單,首先根據哈希值直接找到鍵值對所在的桶,再對桶內的鏈表進行遍歷,找到相應的鍵值對.
有一點注意,在方法中,判斷鍵值對是否同一個的時候,首先對比hash值,然后對比是否同一個引用或
equals()
是否為true.所以放入HashMap內的元素必須覆蓋hashCode()
和equals()
方法。
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
int hash = (key == null) ? 0 : hash(key);
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;
}
put(K,V)
這個方法用于更新或加入鍵值對.可以看出可以分成四個部分
- 如果HashMap為空,調用
inflateTable(threshold)
進行初始化 - 如果鍵值對為{null,X},調用
putForNullKey(value)
- 根據哈希值找到相應桶,遍歷桶內的鏈表找到相應的鍵值對,更新
- 如果找不到相應的鍵值對,在那個桶內加入新鍵值對
addEntry(hash, key, value, i)
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
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))) {
V oldValue = e.value;
e.value = value;
//這個調用沒有意義
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
- inflateTable(threshold)
返回一個初始化后的新桶數組,大小為2的整數冪N,且N>=原閾值
private void inflateTable(int toSize) {
// 返回2的整數冪N,且N>=number
int capacity = roundUpToPowerOf2(toSize);
//更新閾值
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
//用于對hashSeed的調整,這里不用理會
initHashSeedAsNeeded(capacity);
}
//調用這個方法會返回2的整數冪N,且N>=number
//桶數量是2的整數冪
private static int roundUpToPowerOf2(int number) {
// assert number >= 0 : "number must be non-negative";
return number >= MAXIMUM_CAPACITY
? MAXIMUM_CAPACITY
: (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
}
- 當鍵值對存在時,無論key是否為null,都是根據哈希值找到桶,然后對桶內的鏈表遍歷找到相應的鍵值對(和
get()
差不多),然后更新value值.當找不到的時候,都是調用addEntry()
插入新鍵值對
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
/觸發桶擴充,下面再詳細說這個函數.
resize(2 * table.length);
//重新計算哈希值和相應的桶的下標,
//因為擴充后,table.length變了,
//hash()的結果可能變化了(根據是否使用hashSeed)
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
//使用頭插入法,把新插入的鍵值對放在頭部
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++;
}
從上面的代碼可以看到,觸發桶擴充的兩個條件:
- 桶數量>=閾值
- 插入時發生了哈希沖突
每次桶擴充后,桶數量為原來的兩倍
resize()
桶擴充的時間花費與桶和size的數量成正比.
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
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);
}