[TOC]java
hashmap 做爲 java 和 Android 開發中面試的必問問題,頗有必要對其有一個詳細的瞭解。node
這篇文章將會從源碼角度,對其存儲結構,功能實現,擴容優化等進行分析。git
分析版本 java 1.8.0github
在 hashmap 源文件前的註釋中,能夠了解的信息以下:面試
首先從一個例子開始:算法
val map = HashMap<Int, Int>()
map.put(1, 1)
map.get(1)
複製代碼
這是基本的存取操做,下面分別看一下每一行具體作了什麼。數組
首先是 hashmap 的構造方法,建立了一個對象。數據結構
/** * 以指定的容量和擴容因子建立空的 hashmap */
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);
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
// 以 指定的 map 建立 對象
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
複製代碼
源碼中有四個構造方法,其對應的註釋如上,上面提到幾個值,好比容量,擴容因子等,在源碼中有幾個常量定義以下:併發
/** * The default initial capacity - MUST be a power of two. * 初始化的默認 容量 大小, 2的4次冪, 16 */
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;
/** * 鏈表 樹化 閾值 */
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. * 樹 鏈表化 閾值 */
static final int UNTREEIFY_THRESHOLD = 6;
/** * The smallest table capacity for which bins may be treeified. * (Otherwise the table is resized if too many nodes in a bin.) * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts * between resizing and treeification thresholds. * 樹化 的 最小容量 */
static final int MIN_TREEIFY_CAPACITY = 64;
複製代碼
將在稍後做出解釋。app
從結構上來說,使用 數組+鏈表(紅黑樹)實現,也即遇到 hash 衝突時使用鏈表法解決, 以下。
能夠解釋一些基本的概念:
/** * map 的數組 */
transient Node<K,V>[] table;
/** * 保存的節點 */
transient Set<Map.Entry<K,V>> entrySet;
/** * 已存入 map 的元素的大小 */
transient int size;
// hashmap 操做的 的次數記錄
transient int modCount;
// 擴容閾值
int threshold;
// 擴容因子
final float loadFactor;
複製代碼
容量表示 table 的大小,最大爲 MAXIMUM_CAPACITY。
在容量不夠時須要進行擴容,何時能肯定容量不夠,即size > 容量 * 擴容因子 = 擴容閾值
時進行擴容;
默認爲 0.75f。
當鏈表的個數大於8, 因爲存取變慢,將鏈表轉爲 紅黑樹,優化性能;隨着鏈表個數減小,小於 6 時, 又轉爲鏈表。
MIN_TREEIFY_CAPACITY = 64, 這個值表示當 鏈表的個數大於8, 但若是容量小於64,仍是進行擴容,而不是轉換樹。
接下來首先看一下 Node<K, V> 的結構,即上圖中的黑點,map 中保存的元素。
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;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
複製代碼
不難理解,最基本的 hash 節點,在大部分數據結構中都有用到。
接着看一下 put 操做:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
複製代碼
/** * Implements Map.put and related methods * * @param hash : key 的 hash 值 * @param key : key * @param value :value * @param onlyIfAbsent:爲true 時表示,當節點存在時不覆蓋 * @param evict : false 表示有 構造函數調用的方法 * @return value : 返回以前的值,空時返回 null。 */
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 當 table 爲空時驚醒擴容,n表示容量
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 定位 table數組中節點的位置,後面分析。
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
// 若是遇到節點衝突
Node<K,V> e; K k;
// 兩個節點相等,則覆蓋
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 若是是樹節點,此時鏈表長度大於8, 轉爲紅黑樹
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);
// 達到條件,鏈表轉爲樹
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;
}
複製代碼
主要內容在 putVal() 函數裏面。
###桶節點索引定位
這裏有幾個特別重要的地方,同時也顯示出設計的巧妙之處。
if ((p = tab[i = (n - 1) & hash]) == null)) {
tab[i] = newNode(hash, key, value, null);
}
複製代碼
上面代碼表示在 table 中根據下標 i = (n - 1) & hash
定位節點的位置,若是該位置爲存入節點,則建立節點並存入。
首先來看爲何要這樣肯定 hash 桶中的索引位置。在 n 大小的數組中,使用 hash % n 來肯定位置。這裏有個特例, 因爲 hash 桶中的數組大小始終爲 2 的 n次方,因此 可使用 上述方法來計算,效率更高;
此時,衝突就由 hash 來決定:當 hash 不容易重複時,就越不容易衝突,看一下 hash 的計算方法:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
複製代碼
這裏剛開始我也不明白爲甚麼爲進行 高位和低位進行異或運算求 hash。
n 表示 table 的大小,當hash & (n - 1)
時,假設 hash 任意,n 爲 16.
key.hash 1110 1110 1101 1010 0001 0001 0010 0110
n - 1. 0000 0000 0000 0000 0000 0000 0000 1111 (只有低位參與運算)
複製代碼
上圖例子中顯示,若是隻是 key.hash 參與運算,那麼只會是低位參與, 爲了防止衝突,加入高位。因此將高16 位 與 低16位進行異或運算,防止衝突。 設計極爲巧妙
上面提到,桶的大小始終爲爲 2 的n次方,主要在於取模(上有介紹)和擴容時作優化。
那麼構造方法裏傳入的自定義大小時怎麼處理的呢, 回看代碼以下:
this.threshold = tableSizeFor(initialCapacity);
/** * Returns a power of two size for the given target capacity. */
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;
}
複製代碼
對於給定的 cap,將轉化爲大於等於cap 中最小的2的n次方數。這裏稍微說明一下,也是設計極爲巧妙。
n = cap - 1
: 爲了處理 cap 恰好是 2的n次方數, n 爲 高位爲0, 低位爲1 的數:00000111111;
n |= n >>> 1
: 無符號右移 1位。不失通常性(包含上面的結果), 假設一個數位 0000001xxxxx,
任何數從左邊第一個 1 開始,右移動 1 位進行或運算;
0000 001x xxxx
0000 0001 xxxx
0000 0011 xxxx(獲得的結果左邊兩高位爲1)
0000 0000 11xx
0000 0011 11xx(獲得的結果左邊4高位爲1)
複製代碼
其他的計算不用進行了,這個時候能夠保證低位所有位1, 加上最後的 n + 1; 便可獲得結果。
那麼繼續往下, resize() 函數的代碼以下:
/** * Initializes or doubles table size. If null, allocates in * accord with initial capacity target held in field threshold. * Otherwise, because we are using power-of-two expansion, the * elements from each bin must either stay at same index, or move * with a power of two offset in the new table. * 初始化或者擴容爲 2 倍大小。因爲其始終爲2 的 n 次方,因此計算的下標或者相等, 或者偏移 2的 n 次方。 * @return the table */
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table; // 舊數組
int oldCap = (oldTab == null) ? 0 : oldTab.length; //舊 table 的容量
int oldThr = threshold; //舊 table 的閾值
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
}
// 還未初始化,爲0
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr; // 這裏解釋了構造函數爲何將 tablesizefor 賦值 threshold。
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;
@SuppressWarnings({"rawtypes","unchecked"})
// 新建 新容量大小的 節點數組
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// 非初始化,舊 table 有數據
if (oldTab != null) {
// 移動到新 table 裏面
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
// 該下標有節點存在
if ((e = oldTab[j]) != null) {
// 舊鏈表該位置爲置空
oldTab[j] = null;
if (e.next == null)
// 只有一個節點,找到下標賦值
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// 樹的操做
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
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;
// 不用計算 hash, 肯定新 table 中下標的位置
// 後續介紹
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;
}
複製代碼
在上面的過程當中,對if ((e.hash & oldCap) == 0)
做下解釋:
在上面肯定桶下標索引的位置時,使用 hash & (n - 1)
計算獲得,擴容後,這裏的 n 至關於 oldCap。
舉個例子:
0000 0000 0000 0000 0000 0000 0000 1111 (n - 1)
0000 0000 0000 0000 0000 0000 0000 0101 (hash1) -> 0101
0000 0000 0000 0000 0000 0000 0001 0101 (hash2) -> 0101
複製代碼
如上,計算時下標相同, 在同一索引位置。
0000 0000 0000 0000 0000 0000 0001 0000 (oldCap)
0000 0000 0000 0000 0000 0000 0000 0101 (hash1) -> 0101
0000 0000 0000 0000 0000 0000 0001 0101 (hash2) -> 10101
複製代碼
能夠看到,當衝突的節點肯定索引位置時,有兩種可能,在原位置或者 原位置 + oldCap。(由於結果最高位1)
由於根據 (e.hash & oldCap) 的 結果 爲1 便可判斷索引在高位, 爲 0 便可判斷索引在低位。
後續就是利用頭尾節點移動衝突的值,最後返回新 table。
這就是爲何容量大小始終爲 2 的 n 次方的優化點,極爲巧妙。
這個時候回過來看 get 操做:
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
複製代碼
不作過多解釋,有了上面的過程,相信很簡單就能看懂。
在設計良好的 hash 算法中,加上有 MIN_TREEIFY_CAPACITY 的存在,轉成樹的狀況不多遇到,這裏就不對紅黑樹的操做做過多分析,有須要的能夠查看源碼或者相關參考資料瞭解。
/** * Replaces all linked nodes in bin at index for given hash unless * table is too small, in which case resizes instead. */
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// 即便鏈表長度大於8,還要知足容量大於MIN_TREEIFY_CAPACITY
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
複製代碼
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}
複製代碼
能夠獲取 key 的 entry 的集合進行遍歷。
以上就是對 hashmap 存取過程的一個分析,主要有如下幾點
在使用 hashmap 的過程當中,擴容是一個特別耗費時間空間的操做,因此在初始化的時候給一個合適的大小。
另外須要處理併發可使用 ConcurrentHashMap。
瞭解了 hashmap 的擴容,那麼對其餘簡單數據類型的擴容也再是問題,繼續看源碼。