HashMap是基於哈希表實現的,每一個元素是一個key-value對。
目錄
- 數據結構
- 存儲形式
- 初始化
- 擴容
- 查找操作
- 插入操作
- 刪除操作
數據結構
首先,每個元素都有一個hash值,我們看看hash值是如何生成的:
/**
* 將key的哈希值無符號右移16位與低16位的亦或運算。
* 作用:如果key數量較少,高16位的哈希值基本固定不變。將高16位
* 的哈希值也參與運算,使哈希值分佈更均勻,減少hash碰撞
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
原理具體分析見:HashMap源碼註解 之 靜態工具方法hash()、tableSizeFor()(四)
存儲形式
HashMap的數據結構採用數組+單鏈表+紅黑樹的形式(jdk1.8中增加了紅黑樹,當鏈表長度不小於閾值(8)時,將單鏈錶轉換爲紅黑樹,這樣大大減少了查找時間。小於8時轉回爲單鏈表)
下圖很好地展示了HashMap的數據結構,桶的形式分爲單鏈表和紅黑樹兩種結構。
——>接着,我們看看每種結構對應的具體實現:
單鏈表
/**
* 單鏈表中的每個節點
*/
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;
}
}
紅黑樹
/*
*紅黑樹中的每個元素及操作方法(省略)
*/
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
。。。。
}
由於紅黑樹涉及到的問題比較多(節點的數據結構,如何插入節點,如何刪除節點),不在此詳細闡述,可以參考如下資料:
本質上,紅黑樹就是一顆2-3-4數(B樹的一種),插入、刪除節點時以2-3-4樹的方式考慮就簡單多了。
數組(哈希表)
/**
* 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;
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
Node[] table,即哈希桶數組。但是要注意數組的大小:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final int MAXIMUM_CAPACITY = 1 << 30;
並且數組的大小(size)只能是2的冪次方。
——>爲什麼容量只能是2次冪的形式?
當我們想要找到元素在表中的位置時,需要先對hash值取餘數,即hash%n,n代表table的capacity。
源碼中通過**(n-1)&hash**的方式,因爲&運算的效率高於%運算。
這樣數組的長度就必須是2的幕次方,才能等價於hash%n。
初始化
即構造函數,主要需要明確容量和加載因子
- 閾值 = 容量 * 加載因子
- loadFactor = capacity * loadFactor
最主要的構造函數:
/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
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;
//tableSizeFor()方法是將容量轉化爲大於其容量的最小2次冪形式
//注意,初始化時直接將容量賦值到閾值:table的初始化被推遲到了put方法中,
//在put方法中會對threshold重新計算,put方法後面具體分析
this.threshold = tableSizeFor(initialCapacity);
}
我們在看看tableSizeFor(initialCapacity)方法:將容量轉化爲大於等於其容量的最小2次冪形式。
/**
* 找到大於等於initialCapacity的最小的2的冪
*/
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;
}
原理具體分析見:HashMap源碼註解 之 靜態工具方法hash()、tableSizeFor()(四)
擴容
在每次插入元素的時候都需要檢查下map的容量,若小於閾值,則需要擴容。
擴容函數 resize()會遇到三種情況:
- table已初始化有元素——>擴容2倍,更新閾值,複製元素到新table
- table未初始化,但是閾值已確定(有參構造器)——>容量等於閾值,再更新閾值
- table未初始化,閾值也未確定(無參構造器)——>初始容量默認16,更新閾值
注意,在將所有元素複製到新的table(新的capacity)時,不需要像JDK1.7的實現那樣重新計算hash,只需要看看原來的hash值新增的那個bit是1還是0就好了,是0的話索引沒變,是1的話索引變成“原索引+oldCap”
- 詳細分析參見:JAVA源碼分析-HashMap源碼分析(二)
——>具體源碼:
//大前提:capacity都是2次冪形式,擴容到兩倍
//(1)table已有元素
//(2)table未初始化,但是閾值已確定
//(3)若table未初始化,閾值也未確定
//————>最終得到:擴容/或默認容量,初始化table,更新閾值
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//(1)table已有元素——>新容量和閾值擴大到2倍
if (oldCap > 0) {
//若舊容量超過最大值
if (oldCap >= MAXIMUM_CAPACITY) {
//閾值設置最大值
threshold = Integer.MAX_VALUE;
return oldTab;
}
//若舊容量超過16,但新容量(擴大到2倍)小於最大值
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//閾值擴大到2倍
newThr = oldThr << 1; // double threshold
}
//(2)若table未初始化,但是閾值已確定——>新容量等於構造時的閾值——>
//調整新閾值threshold = capacity * loadFactor——>初始化table,但size爲0
//(這種情況出現在:在構造函數中已確定了閾值,在putVal函數(put()插入一個元素、putMapEntries()插入map集等會調用putVal)
//插入元素時調用resize擴容函數)
else if (oldThr > 0) // initial capacity was placed in threshold
/**
* 爲什麼newCap直接等於oldThr,而不是oldThr/loadFactor?
*
* 雖然規定threshold = capacity * loadFactor
* 但在構造函數中直接賦值threshold = capacity
* 所以newCap無需調整
*
*/
newCap = oldThr;
//(3)若table未初始化,閾值也未確定——>初始新容量和閾值——>初始化table,但size爲0
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
//注意這裏的threshold = capacity * loadFactor
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//情況(2)中,將舊閾值threshold = capacity調整新閾值threshold = capacity * loadFactor
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//更新閾值
threshold = newThr;
//初始化table
@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) {
//gc
oldTab[j] = null;
//①如果桶中只有一個元素
if (e.next == null)
//新table的位置
newTab[e.hash & (newCap - 1)] = e;
//②如果桶中不止一個元素,且桶是紅黑樹的形式
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//③如果桶中不止一個元素,且桶是單鏈表的形式
else { // preserve order
//聲明瞭隊尾和隊頭指針。新索引標識(原索引+oldCap)爲hi,原索引標識爲lo
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
//只需要看看原來的hash值新增的那個bit是1還是0就好了,
//是0的話索引沒變,是1的話索引變成“原索引+oldCap”
//不需要對每個元素重新計算hash值
//
// 原索引
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
// 原索引+oldCap
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 原索引放到bucket裏
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
} // 新索引(原索引+oldCap)放到bucket裏
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
查找操作
1、通過key查找元素:
-
public V get(Object key)
-
public boolean containsKey(Object key)
-
@Override public boolean replace(K key, V oldValue, V newValue)
-
。。。。
最終源碼都會調用getNode()方法,通過元素的hash值找到桶的位置後,再檢查桶(單鏈表或紅黑樹)中是否有元素。
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab;
Node<K,V> first, e;
int n; K k;
//①table已經初始化,②且長度大於0,③根據hash尋找到的table中桶也不爲空
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 {
//節點key的哈希值相同且節點key相同
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
2、通過value查找元素:
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
//遍歷
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}
插入操作
插入過程參見下圖:
1、插入單個元素:
// 第三個參數 onlyIfAbsent 如果是 true,那麼不能覆蓋value(除非value爲空)
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未初始化,或長度爲0,則先擴容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//如果找到的桶位置,但爲空,則直接新建節點(單鏈表形式)
if ((p = tab[i = (n - 1) & hash]) == null)
//尾指針爲空
tab[i] = newNode(hash, key, value, null);
//否則查找待插入的元素在桶中是否存在
else {
//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)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//如果桶是單鏈表的形式
else {
for (int binCount = 0; ; ++binCount) {
//(尾插法)如果未找到相同節點,即e=null,在最後插入
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果節點超過8,轉化成紅黑樹形式
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果找到相同節點,保存到e
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();
//LinkedHashMap中被覆蓋的afterNodeInsertion方法,用來回調移除最早放入Map的對象
afterNodeInsertion(evict);
return null;
}
2、插入元素集合:
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
//判斷插入集合大小的有效性
if (s > 0) {
//如果table未初始化
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);
}
//如果table已初始化,但是待插入map的大小直接超過閾值,則需要調整table的大小
//(注意是大小直接超過閾值,不是table剩餘容量)
else if (s > threshold)
resize();
//正式將待插入map一個一個插入
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);
}
}
}
刪除操作
刪除單個元素:
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
//e代表正在搜索的節點,p代表前個節點
Node<K,V>[] tab; Node<K,V> p; int n, index;
//table已經初始化,且長度大於0,根據索引找到的桶的位置不爲空
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);
}
}
//移除找到的節點
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;
}
參考:
- JDK1.8 HashMap源碼分析
- Java8系列之重新認識HashMap
- 【Java集合源碼剖析】HashMap源碼剖析(jdk1.6的源碼,與jdk1.8不同)