這篇文章算是json那篇的番外吧,畢竟是爲了搞清楚那件事,才引出了這件事。
本文只是簡單的看了一下java 8的HashMap源碼,大概只詳細的看了兩個方法,並且參考了幾篇源碼文章:
https://blog.csdn.net/soga613/article/details/78958642
http://www.importnew.com/28263.html
那麼我們就開始吧。
簡介
翻開源碼,首先我們會看到有着篇幅巨大的註解。
開頭就描述了HashMap不保證map中的順序;第二段主要強調了迭代性能優先時,不要將初始容量設置的太大;第三段主要講了兩個重要參數:初始容量
和負載因子
,負載因子是判斷擴容的主要標準;第四段主要講述負載因子的默認值爲(.75),並解釋了爲什麼這麼設置,以及容量超過最大值上限時,不再重新hash;等等等(我們只需要瞭解這麼多就可以繼續接下來的內容了)。
接着我們又能看到另一大串註解。
主要講述了map中,通常是以hash表的形式存在的,但是當每個位置的鏈表過大時,他就轉化爲一個樹形結構,也就是紅黑樹(本文不討論,後續更新)。在樹結構中通常也是以hashCode爲主進行排序,但如果兩個元素符合"class C implements Comparable<C>"
時,就會按照它們的compareTo
方法排序。等等等等。
所以這段註解主要是爲了講述java 8新增的紅黑樹的相關內容。
然後我們就開始看具體的方法代碼。
首先是HashMap的構造函數
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
// MAXIMUM_CAPACITY的值爲1073741824(2^30)
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);
}
而這個計算閾值的方法就是一個非常好的算法
/**
* 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;
}
它的作用是返回據傳入值最近的且比傳入值大的2的n次方。
比如我們傳入3,它返回4;傳入6,返回8,傳入12,返回16等等。
但是我們看到,在構造函數中,並沒有初始化map,這個操作是在對應的putVal方法中進行的。
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;
// 初始化tab數組
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 如果tab中之前的hash映射爲空,則新建一個node
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 已有hash的情況
else {
Node<K,V> e; K k;
// p的hash有映射,且key值正好相等,那就是之前有對應key
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 如果p是樹節點,涉及紅黑樹,忽略
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// p的hash有映射,但是這裏是一個鏈表,所以需要遍歷
else {
for (int binCount = 0; ; ++binCount) {
// 鏈表中沒有對應key,新建node
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 如果超過樹形閾值,則變爲紅黑樹
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 如果鏈表中有對應的key,則e值不爲空,進行下面的覆蓋操作
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;
}
}
// 記錄HashMap結構被修改的次數,在迭代的時候用
++modCount;
// 如果發現容量超過閾值,則進行擴容
if (++size > threshold)
resize();
// 執行插入後方法,忽略
afterNodeInsertion(evict);
return null;
}
上面的過程可以用下面這張圖來總結(偷的)
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
}
// 如果舊錶容量爲0,但舊的閾值大於0(刪除到容量爲0的情況)
else if (oldThr > 0) // initial capacity was placed in threshold
// 新容量使用舊閾值
newCap = oldThr;
// 初始化,使用默認值
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY; // 16
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 12
}
// 新閾值爲0時,第二種情況,用負載因子重新計算
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];
// 擴容後的tab
table = newTab;
// 如果舊tab非空,進行數據遷移
if (oldTab != null) {
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);
// 如果該元素是一個鏈表,將該鏈表分成兩個鏈表,主要根據鏈表對應值的hash值確定
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值
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);
// 原hash對應鏈表
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// 原hash+舊錶容量的鏈表
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
重點說一下(e.hash & oldCap) == 0
,因爲容量翻倍後,之前hash對應的鏈表中就會分爲兩派,舉例,之前的容量爲16,hash爲3的元素存在鏈表,鏈表中存的值有hash爲3和19的,但是它們都在這個元素中,hash爲19是因爲容量限制,所以只能放在這裏,但是當容量翻倍爲32時,hash爲19的值就有自己的在hash tab中的位置了,所以之前的一個鏈表分化爲兩個鏈表。這裏偷一張圖。
所以其實(e.hash & oldCap)
就是計算新增的那個bit位是0還是1,也就是它應該屬於原hash,還是擴容後的hash。
get
到這裏,我們將主體的兩個方法的源碼看完了,還有一個get方法的源碼,不過其實也很簡單。
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// tab非空纔會取到值
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// tab元素下對應hash中的第一個node
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);
// 遍歷鏈表取值,取不到就返回null
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
暫時就將HashMap的源碼看到這裏,已經夠解決我之前的問題了。