參考文章:https://www.cnblogs.com/leesf456/p/5242233.html
1.HashMap結構
table即爲存放元素的數組,桶(bucket)的作用是在key的hash值發生碰撞時將key發生碰撞的元素存入桶中。不難發現1.8的HashMap較之1.7的HashMap做了較大的優化,其中有個比較明顯的地方就是在原來桶中的元素不在按照唯一的鏈表進行存放,而是將鏈表與紅黑樹一起使用。
2.成員變量
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
// 序列號
private static final long serialVersionUID = 362498820763181265L;
// 默認的初始容量是16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默認的填充因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 當桶(bucket)上的結點數大於這個值時會轉成紅黑樹
static final int TREEIFY_THRESHOLD = 8;
// 當桶(bucket)上的結點數小於這個值時樹轉鏈表
static final int UNTREEIFY_THRESHOLD = 6;
// 桶中結構轉化爲紅黑樹對應的table的最小大小
static final int MIN_TREEIFY_CAPACITY = 64;
// 存儲元素的數組,總是2的冪次倍
transient Node<k,v>[] table;
// 存放具體元素的集
transient Set<map.entry<k,v>> entrySet;
// 存放元素的個數,注意這個不等於數組的長度。
transient int size;
// 每次擴容和更改map結構的計數器
transient int modCount;
// 臨界值 當實際大小(容量*填充因子)超過臨界值時,會進行擴容
int threshold;
// 負載因子
final float loadFactor;
}
3.無參構造函數
在無參構造函數是將其負載因子複製爲默認的常數0.75f。
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
4.put函數
我們在調用put函數的時候其實做了兩步操作,一步是計算出key的hash值,一步是調用putVal函數將元素存入table中。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
在計算key的hash值的時候並不是簡單的只取其hash值,而是取其hash值與其hash值做高位補0的無符號右移16位之後的異或運算,個人認爲在這裏做這步操作的原因是爲了將高位參與運算從而減少key的hash值發生碰撞。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
putVal函數,在將元素存入table中的時候,如果需要存入桶中時需判斷桶中的結點是紅黑樹還是鏈表。
紅黑樹:調用putTreeVal函數將元素直接插入紅黑樹中。
鏈表:如果元素重複,則替換元素;如果元素不重複將鏈表中最後一個元素指向新元素,此時如果鏈表的長度大於8,則通過treeifyBin函數將鏈表轉換爲紅黑樹。
爲什麼在長度爲8的時候纔將鏈表轉換爲紅黑樹?
鏈表的平均查找長度爲n/2,紅黑樹的平均查找長度爲log2n,log2 8=3 < 8/2=4,故在長度爲8的時候纔將鏈表轉爲紅黑樹。
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;
// (n - 1) & hash 確定元素存放在哪個桶中,桶爲空,新生成結點放入桶中(此時,這個結點是放在數組中)
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 桶中已經存在元素
else {
Node<K,V> e; K k;
// 比較桶中第一個元素(數組中的結點)的hash值相等,key相等
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 將第一個元素賦值給e,用e來記錄
e = p;
// hash值不相等,即key不相等;爲紅黑樹結點
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;
}
// 判斷鏈表中結點的key值與插入的元素的key值是否相等
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
// 相等,跳出循環
break;
// 用於遍歷桶中的鏈表,與前面的e = p.next組合,可以遍歷鏈表
p = e;
}
}
// 表示在桶中找到key值、hash值與插入元素相等的結點
if (e != null) {
// 記錄e的value
V oldValue = e.value;
// onlyIfAbsent爲false或者舊值爲null
if (!onlyIfAbsent || oldValue == null)
//用新值替換舊值
e.value = value;
// 訪問後回調
afterNodeAccess(e);
// 返回舊值
return oldValue;
}
}
// 結構性修改
++modCount;
// 實際大小大於閾值則擴容
if (++size > threshold)
resize();
// 插入後回調
afterNodeInsertion(evict);
return null;
}
putVal大致流程圖
5.resize函數
在putVal的過程中如果原table爲空或者元素長度超過了閾值(在這裏並不是超過了原長度,而是超過了閾值),會進行HashMap的擴容操作。在其擴容時將長度擴大至原來的2倍,同時其閾值也擴大至原來的2倍。
在resize的過程中會將其中的所有元素進行重新hash,並判斷桶中的結點若爲樹則需要確定其是否需要剪成鏈表,若爲鏈表則需要通過(e.hash & oldCap) == 0來判斷是否需要拆分鏈表放入到不同的桶中。
final Node<K,V>[] resize() {
// 當前table保存
Node<K,V>[] oldTab = table;
// 保存table大小
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 保存當前閾值
int oldThr = threshold;
int newCap, newThr = 0;
// 之前table大小大於0
if (oldCap > 0) {
// 之前table大於最大容量
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)
newCap = oldThr;
// oldCap = 0並且oldThr = 0,使用缺省值(如使用HashMap()構造函數,之後再插入一個元素會調用resize函數,會進入這一步)
else {
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 新閾值爲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"})
// 初始化table
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// 之前的table已經初始化過
if (oldTab != null) {
// 複製元素,重新進行hash
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;
// 將同一桶中的元素根據(e.hash & oldCap)是否爲0進行分割,分成兩個不同的鏈表,完成rehash
do {
next = e.next;
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;
}
resize大致流程爲
6.get函數
我們在調用get函數的時候內部其實是通過getNode函數來獲取元素的,在尋找元素的時候,如果第一個元素就符合查找條件則直接返回,若元素在桶中的紅黑樹節點則通過getTreeNode來找到元素,若爲鏈表結點則遍歷鏈表找到該元素。
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;
// 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 {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}