在上篇部落格中分析了hashmap的用法,詳情檢視java并發之hashmap
本篇部落格重點分析下hashmap的源碼(基于JDK1.8)
一、成員變量
HashMap有以下主要的成員變量
/**
* The default initial capacity - MUST be a power of two.
預設初始容量
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
最大容量
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
預設的加載因子
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
JDK1.8在哈希沖突後,使用連結清單的方式存儲資料,當連結清單中元素個數超過8個,則轉化為紅黑樹的格式
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
當紅黑樹的節點數少于6個,則轉化為連結清單
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
存儲元素的數組
*/
transient Node<K,V>[] table;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* The number of key-value mappings contained in this map.
key-value的個數
*/
transient int size;
上面對HashMap中的主要成員變量做了注釋,重點關注以下幾個,
transient Node<K,V>[] table 這個成員變量是HashMap存儲鍵值對的載體,Node類型的數組,可以聯想到把鍵值對封裝成了Node對象,然後使用數組存儲一個一個的Node,展現了Java三大特性中的封裝。
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; HashMap的預設容量,即table資料組的預設長度,在建構table數組時使用。
static final int MAXIMUM_CAPACITY = 1 << 30 HashMap的最大容量,即table資料的最大長度。
static final float DEFAULT_LOAD_FACTOR = 0.75f 預設的加載因子,這個變量很重要,關系到HashMap擴容以及數組的飽和程度等
final float loadFactor 加載因子
int threshold 代表HashMap的門檻值,=table數組的長度*loadFactor,當HashMap中鍵值對的數量大于threshold的時候便需要擴容,即把資料的長度擴大一倍
二、構造函數
HashMap提供了以下4個構造函數,

1、HashMap()
這個是預設的構造函數,其實作如下
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
從其實作來看,僅指定了預設的負載因子,其他的均為預設值,預設的負載因子為0.75,這個值是經過經驗得出的,是空間和時間上的一個均衡。
2、HashMap(int initialCapacity)
這個可以指定HashMap的初始容量,但此容量并非要建立的Node類型的table的長度,HashMap使用了tableSizeFor(int cap)方法對其處理,此方法下面會說到。構造方法的實作如下,
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
實作即調用了另一個構造方法
3、HashMap(int initialCapacity, float loadFactor)
這個構造方法可以指定兩個參數,一個是初始容量,另一個是負載因子,前面說到容量*負載因子=閥值(threshold),當鍵值對的數量(size)大于閥值時便要擴容。構造方法實作如下,
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;
this.threshold = tableSizeFor(initialCapacity);
}
對給定的初始容量做了判斷,最後通過tableSizeFor函數計算出的值給了threshold。
4、HashMap(Map<? extends K, ? extends V> m)
使用一個Map類型的變量構造HashMap,其實作如下
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
指定了負載因子,看起來負載因子很重要。
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
從4個構造方法中,可以看出都并未初始話table變量,即存儲資料的數組,那麼table變量在什麼時候初始化那,是在put方法中。為什麼要放在put方法中,那是因為如果我就調用了構造方法,然後初始化了table數組,配置設定了記憶體,然而我不向HashMap中放資料,即不調用put方法,那麼肯定會造成記憶體的浪費,是以隻有在真正調用put的時候才初始化table,考慮周全呀。
二、工具函數
這裡重點分析兩個工具函數,hash和tableSizeFor。
1、hash(Object key)
此函數的作用是傳遞一個key參數,傳回一個int數值,
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
如果key為null,則傳回0,否則,取key的hashCode值h和h無符号右移16位的異或值。為什麼要這樣做我們放在後邊分析。這個函數決定了每個鍵值對在table數組中的位置。
2、tableForInt(int cap)
此函數是為了計算大于或等于給定參數的最小的2的N次方。
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
舉個例子,現在給一個數19,調用此函數後傳回32;給一個數16,調用此函數後傳回16,給一個數15,調用此函數後傳回16。
三、put/get操作
put和get操作是HashMap中常用的操作,使用頻率很高,了解其實作對編寫代碼很有提升。
1、put(K key, V value)
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
從上面的代碼中可以看出調用了putVal方法,使用hash函數對key進行了哈希。putVal的定義如下,
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底層的數組table為空,或者其長度位0
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;//調用擴容方法進行擴容,并傳回擴容後的長度
//如果要存儲的key在table中的索引處元素p為null,則說明此key所在索引處未産生hash沖突
if ((p = tab[i = (n - 1) & hash]) == null)
//生成一個Node節點,放在此key的索引處
tab[i] = newNode(hash, key, value, null);
else {//如果此key所在的索引處的元素p不為null,說明已經有其他的key的hash值和現在key的hash相同,産生了hash沖突,兩個元素在table中的索引一緻
Node<K,V> e; K k;
//如果要插入的key value和p的全部相同,把p賦給e
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果不相等,判斷p的節點類型,如果是TreeNode類型,則證明是紅黑樹的結構,調用putTreeVal進行元素插入
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {//如果不是TreeNode類型,則說明是連結清單的結構,使用連結清單的方式插入,找到連結清單的尾部,進行插入
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
//在p後插入元素
p.next = newNode(hash, key, value, null);
//判斷連結清單的元素數量,如果大于8,則調用treeifyBin方法轉化為紅黑樹
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;
}
}
//e不為null,說明存在一個相同的key,則需要進行value的替換,并傳回舊值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//如果插入元素後,元素個數大于threshold(閥值=數組容量*負載因子),進行擴容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
在上面的代碼中做了詳細的注釋,下面把過程概括如下
1、判斷HashMap底層存儲資料的數組table是否為null或者長度為0(這裡在進行table的初始化),如果是則進行擴容(第一次叫初始化);
2、如果不是,取出要插入key在數組中索引位置的元素p,判斷p是否為null,如果為null,則直接插入;
3、如果p不為null,判斷判斷p和待插入資料是否相等,如果相等使用e存儲p(後面會判斷e是否null,如果不為null,則進行值的替換);
4、如果不等,判斷p的類型是否為TreeNode,即是否為紅黑樹的結構,如果是則使用紅黑樹的方式插入;
5、如果不是TreeNode,則使用連結清單的方式插入;
6、插入完成後更新元素的個數size,如果size大于threshold進行擴容;
上面是put的大體過程,對于紅黑樹的插入,暫不做分析,下面分析下擴容函數resize,其源碼如下
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
//1、建立一個新的Node數組,儲存資料
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
//2、如果舊數組不為空,則要把元素拷貝到新數組
if (oldTab != null) {
//循環舊數組中的元素
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//j索引處不為null,取出給e
if ((e = oldTab[j]) != null) {
//清空j處的元素
oldTab[j] = null;
//2.1、判斷e是否有後繼,如果沒有說明僅有一個Node元素,重新計算e中key的hash值,得到在新數組中的索引,進行插入
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
//2.2.1判斷e是否為TreeNode類型,如果是使用紅黑樹的方式
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//2.2.2不是紅黑樹的資料結構,為連結清單結構,進行連結清單結構的資料拷貝
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
在上面源碼中進行了詳細注釋,具體步驟可檢視注釋。
2、get(Object key)
get函數是使用key取出其對于的value的過程,其源碼如下
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
使用getNode函數取出Node元素,如果Node為null,則傳回null,如果不為則傳回其value屬性值,關于Node類的構成稍後分析,先看getNode函數,
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//1、判斷table不為null且長度大于0,且要取的key處索引位置元素不為null
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//2、如果第一個元素和給定的key相等則直接傳回第一個元素first
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
//3.1、如果第一個元素的類型為TreeNode,使用紅黑樹的方式取得Node
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//3.2、使用連結清單的方式取得Node
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
在上面的代碼中進行了詳細注釋,可參考。
下面看下Node的結構,
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
Node作為HashMap的靜态内部類,其屬性有hash、key、value、next,使用這些屬性存儲資料,其中key value即為我們說的hashMap中的鍵值對,這裡使用Node進行封裝。next指向下個Node的位址。
以上對HashMap做了主要分析,後面計劃對其哈希hash函數即紅黑樹做分析。
有不正之處,歡迎指正!