HashMap簡介
JangGwa從源碼角度帶你熟悉一下JDK1.8的HashMap氮采,首先簡單介紹下HashMap殷绍。
1.HashMap有三種數(shù)據(jù)結(jié)構(gòu),數(shù)組鹊漠,鏈表主到,紅黑樹。
2.HashMap是非線程安全的
3.HashMap存儲的內(nèi)容是鍵值對(key-value)映射躯概,key登钥、value都可以為null。
4.HashMap中的映射不是有序的娶靡。
5.實(shí)現(xiàn)了Cloneable接口牧牢,能被克隆。
6.實(shí)現(xiàn)了Serializable接口姿锭,支持序列化塔鳍。
HashMap源碼解析
HashMap繼承了AbstractMap并實(shí)現(xiàn)了Map, Cloneable, java.io.Serializable 接口,上面做了相應(yīng)的介紹就不再闡述了艾凯。關(guān)鍵我們看兩個(gè)重要的屬性initialCapacity,loadFactor献幔。
initialCapacity:初始容量,是哈希表創(chuàng)建中桶的數(shù)量趾诗。
loadFactor:加載因子(默認(rèn)0.75)蜡感,是哈希表在其容量自動增加之前可以達(dá)到多滿的一種尺度。
當(dāng)哈希表中的條目數(shù)超出了加載因子與當(dāng)前容量的乘積時(shí)恃泪,哈希表將具有兩倍的桶數(shù)郑兴。
public class More ...HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
private static final long serialVersionUID = 362498820763181265L;
// 默認(rèn)的初始容量(容量為HashMap中槽的數(shù)目)是16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 最大容量(必須是2的冪且小于2的30次方,傳入容量過大將被這個(gè)值替換)
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默認(rèn)加載因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// list to tree 的臨界值
static final int TREEIFY_THRESHOLD = 8;
// 刪除沖突節(jié)點(diǎn)后贝乎,hash相同的節(jié)點(diǎn)數(shù)目小于這個(gè)數(shù)情连,紅黑樹就恢復(fù)成鏈表
static final int UNTREEIFY_THRESHOLD = 6;
// 擴(kuò)容的臨界值
static final int MIN_TREEIFY_CAPACITY = 64;
// 存儲元素的數(shù)組
transient Node<k,v>[] table;
Node節(jié)點(diǎn)的數(shù)據(jù)結(jié)構(gòu)
// 繼承自 Map.Entry<K,V>
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
// 指向下一個(gè)節(jié)點(diǎn)
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; }
// 返回 Hash 值
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
// 重寫 equals()
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;
}
}
樹節(jié)點(diǎn)數(shù)據(jù)結(jié)構(gòu)
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // 父
TreeNode<K,V> left; // 左
TreeNode<K,V> right; // 右
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red; // 判斷顏色
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
// 返回根節(jié)點(diǎn)
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
HashMap的4個(gè)構(gòu)造函數(shù)
// 默認(rèn)構(gòu)造函數(shù)。
public More ...HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
// 包含“子Map”的構(gòu)造函數(shù)
public More ...HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
// 指定“容量大小”的構(gòu)造函數(shù)
public More ...HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
// 指定“容量大小”和“加載因子”的構(gòu)造函數(shù)
public More ...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;
this.threshold = tableSizeFor(initialCapacity);
}
put函數(shù)
public V put(K key, V value) {
// 對key的hashCode()做hash
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;
// tab為空則創(chuàng)建
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 計(jì)算index览效,并對null做處理
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 節(jié)點(diǎn)存在
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 該鏈為樹
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;
}
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;
// 超過load factor*current capacity却舀,resize
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
get函數(shù)
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;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 數(shù)組元素相等
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 桶中不止一個(gè)節(jié)點(diǎn)
if ((e = first.next) != null) {
// 在樹中g(shù)et
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
// 在鏈表中g(shù)et
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
resize函數(shù)
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) {
// 超過最大值就不再擴(kuò)充了,就只好隨你碰撞去吧
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 沒超過最大值锤灿,就擴(kuò)充為原來的2倍
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 {
signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
// 計(jì)算新的resize上限
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 = newTab;
if (oldTab != null) {
// 把每個(gè)bucket都移動到新的buckets中
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 {
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);
// 原索引放到bucket里
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// 原索引+oldCap放到bucket里
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
總結(jié)
- HashMap有三種數(shù)據(jù)結(jié)構(gòu)挽拔,數(shù)組,鏈表但校,紅黑樹螃诅。
- 如果沖突節(jié)點(diǎn)到8時(shí),就把鏈表轉(zhuǎn)換成紅黑樹;
- 如果bucket滿了(超過load factor*current capacity)术裸,就要resize倘是。
- 在resize的過程,就是把bucket擴(kuò)充為2倍袭艺,之后重新計(jì)算index搀崭,把節(jié)點(diǎn)再放到新的bucket中。
- get()如果有沖突匹表,則通過key.equals(k)去查找對應(yīng)的entry
若為樹门坷,則在樹中通過key.equals(k)查找,O(logn)袍镀;
若為鏈表,則在鏈表中通過key.equals(k)查找冻晤,O(n)苇羡。