1 字段
1.1 字段解讀
//默認容量等於16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//默認加載因子,可以自己調節
static final float DEFAULT_LOAD_FACTOR = 0.75f;
final float loadFactor;
//鏈表轉紅黑樹閾值,當>=8時候,轉化爲紅黑樹
static final int TREEIFY_THRESHOLD = 8;
//樹還原爲鏈表的閾值,當在擴容(resize())時(HashMap的數據存儲位置會重新計算),在重新計算存儲位置後,當原有的紅黑樹內數量 <= 6時,則將 紅黑樹轉換成鏈表
static final int UNTREEIFY_THRESHOLD = 6;
//轉化爲樹的最小容量,當哈希表中的容量 > 該值時,才允許將鏈表 轉換成紅黑樹
static final int MIN_TREEIFY_CAPACITY = 64;
//hashMap的數組,當第一次使用的時候初始化,長度永遠是2的冪次方
transient Node<K,V>[] table;
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the HashMap fail-fast. (See ConcurrentModificationException).
*/
//map結構被修改的次數,比如新增,刪除,擴容等操作
transient int modCount;
//進行擴容的閾值,容量*負載因子即是該值,當大於該值時進行擴容
int threshold;
1.2 待扣細節
這幾個字段會有幾個面試問題:參見文章《JDK8中HashMap源碼細節死扣》
- 爲什麼負載因子默認是0.75?
- 爲什麼鏈表長度>=8纔會樹化?
- 爲什麼容量必須是2的冪次方?
- modCount是用來幹嘛的?
- Map容量爲什麼不能爲MAX_VALUE
2 內部類
2.1 Node<K,V>
static class Node<K,V> implements Map.Entry<K,V> {
//key的哈希值
final int hash;
final K key;
V value;
//下一個節點
HashMap.Node<K,V> next;
Node(int hash, K key, V value, HashMap.Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}
2.2 TreeNode<K,V>
final class TreeNode extends LinkedHashMap.Entry {
TreeNode parent; // red-black tree links
TreeNode left;
TreeNode right;
TreeNode prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node next) {}
// 返回當前節點的根節點
final TreeNode root() {
for (TreeNode r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
}
3 初始化
3.1 源碼
有多個初始化方法,這裏就選一個
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(initialCapacity) 作用?
this.threshold = tableSizeFor(initialCapacity);
}
//保證函數返回值是大於等於給定參數initialCapacity最小的2的冪次方的數值//比如傳進來是15,那麼得到的是16//傳進來是17,那麼大於它的最小2次冪是32,所以得到32
static final int tableSizeFor(int cap) {
//給定的cap 減 1,爲了避免參數cap本來就是2的冪次方,這樣一來,經過後續操作,cap將會變成2 * cap
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n = MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
3.2 待扣細節
這裏運算不做說明,參見文章《JDK8中HashMap源碼細節死扣》
4 put(key,value)
4.1 源碼
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//key的哈希算法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node[] tab; //map的數組
Node p;
int n, i;//n是數組的長度,i是當前要進入put的元素所在數組的index
if ((tab = table) == null || (n = tab.length) == 0)//如果數組爲null或者長度爲0,則進行初始化 ,相當於懶加載,第一次put的 時候進行初始化
//這裏就是初始化的resize()擴容
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
//tab[i]沒有Node,也就是沒有hash衝突,則new一個Node,並複製到數組
tab[i] = newNode(hash, key, value, null);
else {//tab[i]不是空,也就是hash衝突了
Node e; K k;
//如果key一樣,則覆蓋節點
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)//如果該節點是紅黑樹的節點
e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
else {//不是紅黑樹,是鏈表
for (int binCount = 0; ; ++binCount) {
//從頭開始遍歷鏈表
if ((e = p.next) == null) {
//遍歷到最後一個Node,則新建一個Node,插入到尾部,上一個Node的next指針指向新的Node
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1)
//當鏈表長度>=8,進行轉化爲紅黑樹
//當hash表容量小於最小轉紅黑樹容量(64),不轉變紅黑樹,只擴容
treeifyBin(tab, hash);
break;
}
//遍歷過程中,發下key一樣,則跳出循環
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//如果key原來是存在的,則返回原來的舊值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
//賦值爲新值
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//走到這裏,代表原先map中不存在該key值
//修改次數+1,如果key是存在的,在上面已經return了,不算做修改次數+1
++modCount;
//當容器容量大於閾值,進行擴容
//在java8中,擴容的時機是插入值後,再擴容,再java7中,如果大於閾值,是先擴容再插入。
if (++size > threshold)
//擴容
resize();
afterNodeInsertion(evict);
//因爲key不存在,所以原先是沒有值的,返回null
return null;
}
/**
* 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;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) //當hash表容量小於最小轉紅黑樹容量(64),不轉變紅黑樹,只擴容
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);
}
}
4.2 流程圖
上面大致邏輯如下圖:
4.3 待扣細節
- key如何hash計算?
- 根據key的hashi值,數組小標如何確定的?tab[(n - 1) & hash]
參見文章《JDK8中HashMap源碼細節死扣》
5 resize()
5.1 源碼
/**
* 擴容有2種使用情況:1.初始化哈希表(第一次put操作) 2.當前數組容量達到擴容閾值
*/
final Node[] resize() {
Node[] oldTab = table;//拷貝舊數組
int oldCap = (oldTab == null) ? 0 : oldTab.length;//舊map容量
int oldThr = threshold;
int newCap, newThr = 0;
// 針對情況2
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
//擴容前的數組容量超過最大值,則不再擴容
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 針對情況2:若無超過最大值,就擴充爲原來的2倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
//newCap設置爲oldCap的2倍並小於MAXIMUM_CAPACITY,且大於默認值, 新的threshold增加爲原來的2倍
newThr = oldThr << 1; // double threshold
}
// 針對情況1:初始化哈希表
else if (oldThr > 0) // initial capacity was placed in threshold
// threshold>0, 將threshold設置爲newCap,所以要用tableSizeFor方法保證threshold是2的冪次方
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;
@SuppressWarnings({"rawtypes","unchecked"})
// 新生成一個table數組
Node[] newTab = (Node[])new Node[newCap];
table = newTab;
if (oldTab != null) {
// oldTab 複製到 newTab,遍歷數組
for (int j = 0; j < oldCap; ++j) {
Node e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
// 如果只有一個節點,則直接賦值
//爲什麼要重新Hash呢?因爲長度擴大以後,Hash的規則也隨之改變。
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// e爲紅黑樹的情況
((TreeNode)e).split(this, newTab, j, oldCap);
else { // preserve order
//之所以定義兩個頭兩個尾對象,是由於鏈表中的元素的下標在擴容後,要麼是原下標+oldCap,要麼不變
Node loHead = null, loTail = null;
Node hiHead = null, hiTail = null;
Node next;
do {
next = e.next;
//e.hash & oldCap,計算下標是否需要移動
// 下標沒有改變
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);
// 原下標對應的鏈表
if (loTail != null) {
//尾部節點next設置爲null
loTail.next = null;
newTab[j] = loHead;
}
// 原索引+oldCap對應的鏈表
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
5.2 待扣細節
- 容量爲啥有最大限制?
- 擴容時候,下標是否需要移動怎麼判定的?
參見文章《JDK8中HashMap源碼細節死扣》
6 get(key)
6.1 源碼
public V get(Object key) {
Node e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node getNode(int hash, Object key) {
Node[] tab; Node 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 總是檢查第一個Node
((k = first.key) == key || (key != null && key.equals(k))))
//命中key直接返回
return first;
//走第一個Node沒有命中key的邏輯
if ((e = first.next) != null) {
//如果大於一個Node
if (first instanceof TreeNode)
//如果是紅黑樹,則從樹中去查找
return ((TreeNode)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;
}
7 總結
在Java8中,HashMap是一個數組+鏈表+紅黑樹的數據結構,如圖所示。
在第一次put操作時候進行首次擴容,數組長度即爲最大容量,當put一個元素時候,會根據key進行hash計算定位到數組下標,如果有hash衝突的話則進行鏈表插入(尾插),當鏈表長度大於8的時候,會轉變爲紅黑樹(注意:當hashmap最大容量還沒達到64時候,不會樹化,而是擴容)。當元素容量達到閾值時候,則進行擴容,是在插入元素後,才進行擴容,而不是先擴容再插入。擴容是按照原容量的兩倍進行擴容,會根據key的hash值判斷是留在原下標位置,還是原下標+擴容前容量的下標位置。