說明
JDK版本jdk1.8.0_191
1. 核心數據結構
首先了解一下繼承體系:
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
public abstract class AbstractMap<K,V> implements Map<K,V>
再看看內部數據結構表示;
HashMap內部維護了一個table字段,我們簡單稱之爲表,這個表是一個節點數組
。
table字段的說明:
table首次使用的時候才初始化,並且在必要的時候會改變大小(resize)。當被初始化分配內存時,它的長度應該總是2的冪(在某些操作下可以容許長度爲0)
/**
* 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;
再看Node數據結構:
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
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;
}
}
Node數據結構很簡單,主要點就在那4個字段
上,函數很簡單。
Node是一個hash節點。通過字段Node<K,V> next;
,可以知道,該數據結構是一個鏈表
。
也就是說HashMap的數據結構
可以用如下的圖形來表示,首先是一個table,表示Node數組,而數組的每個元素都是一個Node鏈表。也就是說
table數組中每個位置的元素都被當成一個桶,每個桶存放一個鏈表,而同一個鏈表存放hash值與散列桶取模運算結果相同的節點
很顯然,查找操作爲:
計算鍵值對所在的桶
在鏈表上進行順序查找
2. HashMap#put
現在分析HashMap#put
。
放入key-value鍵值對到map中,如果map中已經存在了此key,舊的value將會被替換成新的。返回值爲被替換的value值;或者當此key之前並不存在,返回null;亦或者之前存在着鍵值對key->null
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
先計算hashcode並將高位哈希碼傳播到低位。由於table使用的是2的冪掩碼,只變化在當前掩碼之上的位的哈希集總是會引起衝突。(例如小表中的連續浮點數key)。所以我們做一個改變:將高位的影響傳播到低位。這樣能做到速度,功用,位傳播質量的權衡。
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
這裏的hash函數,我們可以稱之爲 “擾動函數"
,由於hashcode是一個int類型的值,它的大小爲[-2^31, 2^31-1]
,如果我們直接拿他作爲hash key的話,顯然很難發生衝突,但是計算機的容量顯然沒有這麼大。
現在使用的方法就是將其右移16位,再與自身做異或運算
,顯然,這將高16位,低16位都參與了運算,並且儘量使低16位混淆。由於table的長度總是2的整數次冪,2的整數次冪有個性質,就是hash % n就相當於hash & (n-1),其中n表示table長度
,這樣,通過與運算,得到了數組的下標。
再看put方法調用的子方法:HashMap#putVal
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
// tab就是table字段的引用
// n爲table的長度
// i 爲 (n - 1) & hash
// 也就是由hash所確定的桶在table中的位置
// p節點就是上面i所確定的桶的節點,也可以認爲是桶確定的鏈表的頭節點
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 之前在分析table字段時說過,table是延遲初始化
// 也就是在首次使用的時候才初始化
// 這裏resize後面再討論,我們現在知道,這個是一個初始化操作
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 如果hash所確定的桶在table中的位置還沒有被佔過位置
// 那麼我們需要給它分配一個Node空間,並且佔位
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else { // hash所確定的桶已經存在位置了
// 那麼根據我們之前對數據結構的分析,此時應該將節點插入到此桶確定的鏈表中
// e就是插入後的返回的節點(或者將要替換的節點)
Node<K,V> e; K k;
// 如果待插入的節點就是鏈表的根節點的話
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
// 如果是紅黑樹表示的節點的話
// TODO 這裏我們先不討論,後面專門進行討論
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);
// 如果達到threshold,那麼就將hash所確定的桶鏈表樹形化
// TODO 這裏也根上面一樣,先不討論
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如果找到了的話,應該是待替換值的節點引用
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value; // 替換
afterNodeAccess(e);
return oldValue;
}
}
// modCount++表示對HashMap進行了修改,fail-fast需要用到
++modCount;
// 如果大小已經超過允許的閾值,則resize
if (++size > threshold)
resize();
// 節點插入之後的操作
afterNodeInsertion(evict);
return null;
}
上面有兩個細節我們暫時沒有討論到,就是resize函數
,還有跟Tree相關的代碼段:p instanceof TreeNode
和treeifyBin(tab, hash)
總的來講put方法的邏輯如下:
而對於resize
,下面討論,也就是我們常說的HashMap的擴容
3. HashMap#resize
說到HashMap的擴容,我們就需要了解HashMap中的幾個參數字段:
參數 | 含義 |
---|---|
capacity | table 的容量大小,默認爲 16。需要注意的是 capacity 必須保證爲 2 的 n 次方 |
size | 鍵值對數量 |
threshold | size 的臨界值,當 size 大於等於 threshold 就必須進行擴容操作 |
loadFactor | 裝載因子,table 能夠使用的比例,threshold = capacity * loadFactor |
/**
* The default initial capacity - MUST be a power of two.
*/
// 默認初始容量(capacity),必須是2的冪,這裏是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.
*/
// 最大的容量,必須是2的冪,這裏是2^31
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.
*/
// 當鏈表長度超過TREEIFY_THRESHOLD,桶的節點開始使用樹來表示,而非鏈表。
// 至少添加節點到TREEIFY_THRESHOLD這麼多數量,節點就被轉化爲樹。
// 此值必須比2大,設置爲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.
*/
// 在resize操作時,由樹轉化爲鏈表的界限值
// 此值應該比TREEIFY_THRESHOLD小,最大是6,用來契合移除元素時的縮水檢測
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.
*/
// 節點被樹形化的最小表容量
// 至少時4倍TREEIFY_THRESHOLD,用來避免resize和樹形化閾值衝突
static final int MIN_TREEIFY_CAPACITY = 64;
HashMap#resize
初始化或者雙倍擴容表的大小。如果表還爲null,則分配初始容量大小爲threshold。否則,由於我們使用的是2的冪擴容,所以每個節點元素必須要麼保持原索引,要麼放在新表中的2的冪偏移位置。
/**
* 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.
*
* @return the table
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
// 舊容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 舊threshold閾值
int oldThr = threshold;
// 新閾值,新容量
int newCap, newThr = 0;
// oldCap > 0 說明是已經初始化過的
if (oldCap > 0) {
// 如果舊容量大於最大容量
if (oldCap >= MAXIMUM_CAPACITY) {
// 把閾值開到最大Integer.MAX_VALUE
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// 新閾值 = 舊閾值 * 2
newThr = oldThr << 1; // double threshold
}
// oldCap <= 0,我們認爲仍然沒有初始化過
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
// 注意threshold爲 load * cap
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;
if (oldTab != null) {
// 遍歷,把oldTable全部重新插入新的table中
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
// 釋放舊的table值,舊的table值交由e引用
oldTab[j] = null;
// 將舊鍵值對”插入“到新的table中
// 如果鏈表爲單節點
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;
// 直接索引,無偏移
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else { // 原索引 + oldCap
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;
}
然而,擴容會引發如下問題,下面的rehash
也就是上面的重新插入到新的table中。
4. HashMap#get
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
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;
}
5. HashMap#remove
/**
* Removes the mapping for the specified key from this map if present.
*
* @param key key whose mapping is to be removed from the map
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
// 如果恰好匹配的就是桶節點
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
// 如果是樹的話,到樹裏去查找
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
// 遍歷鏈表查找
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
// 找到了需要刪除的節點node
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
// 刪除樹中節點
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
// 刪除鏈表中的節點
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}