JDK 1.7 中 HashMap 是以數組加鏈表的形式組成的;
JDK 1.8 之後新增了紅黑樹的組成結構,當鏈表大於 8 並且容量大於 64 時,鏈表結構會轉換成紅黑樹結構.
JDK 1.8 之所以添加紅黑樹是因爲一旦鏈表過長,會嚴重影響 HashMap 的性能,而紅黑樹具有快速增刪改查的特點,這樣就可以有效的解決鏈表過長時操作比較慢的問題。
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
// hashMap初始化長度
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// hashmap的最大長度
static final int MAXIMUM_CAPACITY = 1 << 30; // 1073741824
// 默認加載因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 當鏈表長度大於此值且容量大於64時
static final int TREEIFY_THRESHOLD = 8;
// 轉換鏈表的臨界值,當元素小於此值時,會將紅黑樹結構轉爲鏈表結構
static final int UNTREEIFY_THRESHOLD = 6;
// 最小樹容量
static final int MIN_TREEIFY_CAPACITY = 64;
// get 方法
public V get(Object key) {
Node<K,V> e;
// 對key進行哈希操作
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) {
// 如果第一個節點是數結構,則使用getTreeNode 獲取對應的數據
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do { // 非樹結構,循環節點判斷
// hash相等且key相同則返回次節點
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
// put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 哈希表爲空則創建表
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 根據 key的哈希值計算出要插入的數據索引 i ;
if ((p = tab[i = (n - 1) & hash]) == null)
// 如果 tab[i] 等於null,則直接插入
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 如果key已存在,直接覆蓋value
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 如果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 已經存在直接覆蓋value
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();
afterNodeInsertion(evict);
return null;
}
// 擴容
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;
}
// 擴大容量爲當前容量的兩倍 ,但不能超過 MAXIMUM_CAPACITY
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// 當前數組沒有數據,使用初始化的值
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
// 如果初始化的值爲0 ,則使用默認初始化容量
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"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
// 開始擴容,將新的容量賦值給table
table = newTab;
// 原數據不爲空,將原數據複製到新table中
if (oldTab != null) {
// 根據容量循環數組,複製費控元素到新table中
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
// 鏈表複製,JDK 1.8 擴容優化部分
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;
}
// 原索引 + oldCap
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;
}
// 將原索引 + oldCap 放到哈希桶中
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
// hash的計算
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
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;
}
}
}
加載因子爲什麼是0.75而不是0.5或者1.0呢?
1. 這其實是出於容量和性能之間平衡的結果:當加載因子設置比較大的時候,擴容的門檻就被提高了,擴容發生的頻率比較低,佔用的空間會比較小,但此時發生Hash衝突的機率就會提升,因此需要更復雜的數據結構來存儲元素,這樣對元素的操作時間就會增加,運行效率也會因此降低;
2. 而當加載因子值比較小的時候,擴容的門檻會比較低,因此會用更多的空間,此時元素的存儲就比較稀疏,發生哈希衝突的可能性就比較小,因此操作性能會比較高。
所以綜合了以上情況就取了一個 0.5 到 1.0 的平均數 0.75 作爲加載因子。