數(shù)據(jù)結(jié)構(gòu)
- 在 JDK1.8 中丧鸯,HashMap 是由 數(shù)組+鏈表+紅黑樹構(gòu)成(JDK1.7是數(shù)組+鏈表)
- HashMap中一些重要成員變量
# 初始化容量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
# 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
# 默認(rèn)負(fù)載因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
# 鏈表轉(zhuǎn)紅黑樹閾值
static final int TREEIFY_THRESHOLD = 8;
# 紅黑樹轉(zhuǎn)鏈表閾值
static final int UNTREEIFY_THRESHOLD = 6;
# 鏈表轉(zhuǎn)紅黑樹Hash表的最小容量閾值
static final int MIN_TREEIFY_CAPACITY = 64;
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;
}
}
public HashMap(int initialCapacity, float loadFactor) {
// 校驗(yàn)參數(shù)
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最小的2冪次方
this.threshold = tableSizeFor(initialCapacity);
}
/**
* 找到大于或等于initialCapacity最小的2冪次方
*/
static final int tableSizeFor(int cap) {
/**
* 確保找到的值大于或等于cap最小的2冪次方:比如cap等于8疙赠,
* 剛好為2的冪次方,如果不進(jìn)行減一操作柴钻,最終的結(jié)果為16硬耍,顯然不正確
*/
int n = cap - 1;
/**
* 該算法讓最高位的1后面的位全變?yōu)?
* 例如:cap = 10 即二進(jìn)制為:1010
* 1010 | 0101 = 1111
*/
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;
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
源碼分析
public V put(K key, V value) {
// 計(jì)算key的hash值
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
// key的hash值高16位與低16位做異或操作愉镰,增加地位的隨機(jī)性订讼,減少hash沖突
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
// 數(shù)組為空,進(jìn)行初始化征讲,
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
// 變量p保存前一個節(jié)點(diǎn)
// 沒有hash沖突的情況据某,新增node節(jié)點(diǎn),保存在數(shù)組下標(biāo)i的位置
tab[i] = newNode(hash, key, value, null);
else {
// hash沖突的情況诗箍,e:已存在的節(jié)點(diǎn)
HashMap.Node<K,V> e; K k;
// 通過key查找node節(jié)點(diǎn)
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof HashMap.TreeNode)
// 查找紅黑樹
e = ((HashMap.TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 查找鏈表
for (int binCount = 0; ; ++binCount) {
// p.next == null癣籽,遍歷到鏈表的末尾,沒有找到key對應(yīng)的節(jié)點(diǎn),則新增節(jié)點(diǎn)放到鏈表的末尾
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 如果節(jié)點(diǎn)數(shù)量大于鏈表轉(zhuǎn)紅黑樹的最小閾值筷狼,則由鏈表轉(zhuǎn)換為紅黑樹
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 節(jié)點(diǎn)已存在瓶籽,onlyIfAbsent為true則不替換舊值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// 修改次數(shù)自增
++modCount;
// 數(shù)組大小大于閾值,則進(jìn)行擴(kuò)容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
final HashMap.Node<K,V>[] resize() {
HashMap.Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
// oldCap > 0埂材,說明數(shù)組已初始化
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// 按當(dāng)前數(shù)組長度的兩倍擴(kuò)容塑顺,閾值也變?yōu)樵瓉淼膬杀? newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
// 數(shù)組未初始化,并且閾值大于零俏险,說明是調(diào)用HashMap(int initialCapacity, float loadFactor)或HashMap(int initialCapacity)構(gòu)造函數(shù)
// 新容量為數(shù)組的閾值
newCap = oldThr;
else { // zero initial threshold signifies using defaults
// 數(shù)組未初始化严拒,并且閾值小于零,說明是調(diào)用HashMap()構(gòu)造函數(shù)
// 新容量為默認(rèn)的初始容量16
newCap = DEFAULT_INITIAL_CAPACITY;
// 新閾值為16 * 0.75
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;
// 創(chuàng)建新數(shù)組
@SuppressWarnings({"rawtypes","unchecked"})
HashMap.Node<K,V>[] newTab = (HashMap.Node<K,V>[])new HashMap.Node[newCap];
table = newTab;
// 舊數(shù)組不為空竖独,則遍歷就數(shù)組并映射到新數(shù)組
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
HashMap.Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// 如果只有一個節(jié)點(diǎn)裤唠,則重新計(jì)算并放入新數(shù)組
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof HashMap.TreeNode)
// 如果是紅黑樹,則進(jìn)行拆分
((HashMap.TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
// 如果是鏈表
HashMap.Node<K,V> loHead = null, loTail = null;
HashMap.Node<K,V> hiHead = null, hiTail = null;
HashMap.Node<K,V> next;
do {
next = e.next;
// e.hash & oldCap预鬓,若為0巧骚,則索引位置不變赊颠;不為0格二,則新索引= 原索引 + 原數(shù)組長度
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;
}
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final HashMap.Node<K,V> getNode(int hash, Object key) {
HashMap.Node<K,V>[] tab; HashMap.Node<K,V> first, e; int n; K k;
// 判斷數(shù)組不為空,并且根據(jù)hash值計(jì)算數(shù)組下標(biāo)竣蹦,沒有節(jié)點(diǎn)直接返回null
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 判斷第一個節(jié)點(diǎn)是否是要查找的顶猜,如果是則返回
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
// 如果節(jié)點(diǎn)類型是紅黑樹,則調(diào)用紅黑樹的方法獲取節(jié)點(diǎn)痘括,否則遍歷鏈表查找
if (first instanceof HashMap.TreeNode)
return ((HashMap.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;
}
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final HashMap.Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
HashMap.Node<K,V>[] tab; HashMap.Node<K,V> p; int n, index;
// 變量node存儲要刪除的節(jié)點(diǎn)
// 判斷數(shù)組不為空长窄,通過hash值計(jì)算對應(yīng)的數(shù)組下標(biāo),并且節(jié)點(diǎn)存在
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
HashMap.Node<K,V> node = null, e; K k; V v;
// 判斷數(shù)組下標(biāo)index的第一個元素是否是查找的元素
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
// 首個節(jié)點(diǎn)不是查找的節(jié)點(diǎn)纲菌,判斷節(jié)點(diǎn)類型
if (p instanceof HashMap.TreeNode)
// 節(jié)點(diǎn)類型是紅黑樹挠日,則調(diào)用紅黑樹的方法查找要刪除的節(jié)點(diǎn)
node = ((HashMap.TreeNode<K,V>)p).getTreeNode(hash, key);
else {
// 節(jié)點(diǎn)類型是鏈表,遍歷鏈表翰舌,查找要刪除的節(jié)點(diǎn)
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)))) {
// 刪除節(jié)點(diǎn)類型是紅黑樹嚣潜,則調(diào)用紅黑樹的方法刪除節(jié)點(diǎn)
if (node instanceof HashMap.TreeNode)
((HashMap.TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
// 刪除節(jié)點(diǎn)是首個節(jié)點(diǎn)
tab[index] = node.next;
else
// 刪除節(jié)點(diǎn)非首個節(jié)點(diǎn),執(zhí)行鏈表刪除
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
為什么要把數(shù)組長度設(shè)計(jì)為2的冪次方
- 當(dāng)數(shù)組長度為2的冪次方時(shí)椅贱,可以使用位運(yùn)算來計(jì)算元素在數(shù)組中的下標(biāo)
HashMap數(shù)組下標(biāo)的計(jì)算公式(n - 1) & hash懂算,等價(jià)于hash%length,也就是對數(shù)組長度求模取余庇麦,
只有當(dāng)數(shù)組長度為2的冪次方時(shí)计技,hash&(length-1)才等價(jià)于hash%length,使用位運(yùn)算可以提高效率山橄。
- 增加hash值的隨機(jī)性垮媒,減少hash沖突