一、hashmap 數據結構
HashMap 主要的操作一般包括:
- V put(K key, V value)
- V get(Object key)
- V remove(Object key)
- Boolean containsKey(Object key)
jdk7 之前的hashmap
HashMap內部存儲數據的方式是通過內部類Entry 來實現的,其中Entry 類的結構如下:
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;//key 的hash 值
Entry<K,V> next;//指向該entry下一個元素
int hash;
}
HashMap put操作
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)//key 為null,
return putForNullKey(value);
int hash = hash(key);//獲取key 的hash 值
int i = indexFor(hash, table.length);//將hash 值映射到數組中對應的索引位置
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))) {//如果該元素在hashmap 中已存在,則替換原有的值
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);//添加新的entry 元素到hashmap 中
return null;
}
hashmap內部存儲的結構,其實就是一個entry 的數組,然后數組的每個位置(也稱之為bucket)存儲的是一個entry 的單鏈表,如下圖所示。
- hash(key)相同的元素,存放在同一個entry 單鏈表中,
- 不同的元素,存放在entry 數組中不同的bucket中
當進行get (key) 操作時,首先會計算key對應在數組的位置,然后根據key 的equal() 方法,遍歷entry 單鏈表 ,找到對應key 的值,反之 put(key,value)操作時類似,不同之處在于,是將該元素插入到entry 鏈表的頭部。
整個bucket 鏈表的形成過程可以分為如下幾步:
- 獲取key 的hashcode 值
- 為了減少hash 沖突,需要對hashcode 值進行rehash 操作 (java8中hashcode右移16位 與hashcode 做異或運算,即高位與低位)
- 為了讓元素存放到數組中對應的索引位置,需要對rehash 后的值與(數組長度-1)進行位運算。
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).
//讓hashcode 的每一位都參與到了運算中來,減少了hash 沖突的發生
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
return h & (length-1);
}
hashmap 什么情況下出現單鏈表
在createEntry方法中,主要有兩步操作:
-
Entry<K,V> e = table[bucketIndex]
獲取數組中原來索引index位置的entry對象。 - 創建一個新的entry 對象 放入到數組中索引index位置處,
table[bucketIndex] = new Entry<>(hash, key, value, e);
,從Entry 的構造函數就可以知道,如果原來的索引index位置的數據對象e 不為null,則此時新entry對象next->e。
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
/**
* Like addEntry except that this version is used when creating entries
* as part of Map construction or "pseudo-construction" (cloning,
* deserialization). This version needn't worry about resizing the table.
*
* Subclass overrides this to alter the behavior of HashMap(Map),
* clone, and readObject.
*/
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++;
}
hashmap 擴容操作
hashmap 的一系列操作(get,put,remove)都會涉及到map中單鏈表的key遍歷查找操作,假使忽略修改操作,這也是一個非常消耗性能的issue,例如,hashmap 的數組大小為16,存放20w的數據,在這種場景下,每一個entry 鏈表的平均大小為20w/16,這種情況之下一個key 的遍歷查找次數和一個很可怕的數字,在這種情況之下,為了避免這種長度巨大的單鏈表的產生,hashmap有了一個自動擴容的操作,即resize。下面兩個圖,分別展示了擴容前后map 中數據分布情況。
hashmap 的默認初始大小為16
DEFAULT_INITIAL_CAPACITY = 1 << 4
,負載因子為DEFAULT_LOAD_FACTOR = 0.75f
為什么hashmap 不是線程安全的?
因為,在hashmap 自動擴容的過程中,get和put 操作時,有可能獲得是擴容前的數據,更糟糕的情況是,并發情況下,多個線程同時進行put 操作,此時可能會引起resize 操作,導致entry 鏈表中形成一個循環鏈表。
jdk8 hashmap
java8 中hashmap 有了很大的改進,java8 中hashmap 內部還是通過數組的存儲方式,只不過,數組中存儲的單元由java7 中的Entry 換成了Node,但是類結構和包含的信息是一樣的,與java7 最大的不同之處在于Node 可以擴展成TreeNode,其中TreeNode 可以擴展成紅黑樹的數據結構,如下圖所示。
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
什么情況下擴展成紅黑樹呢?
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//當前hashmap 為空,觸發map 的自動擴容resize 操作
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//i = (n - 1) & hash 就是java7 中的indexFor 的操作,判斷數組當前位置是否已經為空,如果為空,就實例化一個node,將該node放入數組中這個索引位置
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//key 存在,就替換掉原有的value,與java 7 類似
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//當單鏈表的長度大于等于TREEIFY_THRESHOLD - 1時,鏈表就轉換成一棵紅黑樹了
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
為什么HashMap 數組大小是2的冪次方
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
return h & (length-1);
}
假如數組的長度為17,參與位運算值為length-1=16,對應的二進制為0000,....,0001,0000,此時任意一個數h與16 進行位運算,結果只有16,0兩種結果,這意味著數組只有兩個bucket,再有元素存放hashmap 時,必然會發生hash 沖突,導致hashmap 變成了兩個單鏈表。
而假如數組長度為16,參與位運算的值為15,對應的二進制為0000,....,0000,1111,,此時任意一個數與15 位運算后,結果必然在[0,15]之間,這剛好對應著數組的下標索引。
這就是為什么hashmap 中數組的大小必須為2 的冪次方。
為什么 hashmap 會出現死循環
參考
疫苗:JAVA HASHMAP的死循環
JDK7與JDK8中HashMap的實現
How does a HashMap work in JAVA
(譯)Java7/Java8中HashMap解析