HashMap
HashMap是以鍵值對(duì)進(jìn)行存儲(chǔ)的集合蒲肋,其中鍵值是唯一的,HashMap是無(wú)序的钝满。
改變
1.7版本的HashMap使用的數(shù)組+鏈表的存儲(chǔ)方式兜粘。
1.8版本的HashMap使用的數(shù)組+鏈表或者數(shù)組+紅黑樹(shù)的存儲(chǔ)方式,當(dāng)鏈表長(zhǎng)度大于某值時(shí)弯蚜,鏈表就會(huì)轉(zhuǎn)化為紅黑樹(shù)孔轴。當(dāng)紅黑樹(shù)節(jié)點(diǎn)數(shù)小于某值時(shí)會(huì)轉(zhuǎn)化為鏈表。雖然存入操作變得復(fù)雜碎捺,但是提高了查詢的效率距糖。
源碼分析
首先看一下重要的屬性。
//數(shù)組的最小容量2的4次方 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//數(shù)組的最大容量2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;
//默認(rèn)加載因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//當(dāng)鏈表長(zhǎng)度大于該值牵寺,鏈表轉(zhuǎn)化為紅黑樹(shù)。
static final int TREEIFY_THRESHOLD = 8;
//當(dāng)紅黑樹(shù)節(jié)點(diǎn)小于該值恩脂,紅黑樹(shù)轉(zhuǎn)化為鏈表帽氓。
static final int UNTREEIFY_THRESHOLD = 6;
//擴(kuò)容的閥值,當(dāng)(加載因子 * 元素個(gè)數(shù))大于閥值就會(huì)進(jìn)行resize操作進(jìn)行擴(kuò)容俩块。
int threshold;
//加載因子
final float loadFactor;
構(gòu)造方法
public 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);
}
//找到容量的最近二次冪的值
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;
}
這里有一個(gè)問(wèn)題延伸黎休,為什么數(shù)組長(zhǎng)度一定是2的倍數(shù)?
一共有兩點(diǎn)原因:
(1)在數(shù)組長(zhǎng)度h是2的冪次時(shí)候h & (length - 1) 與 h % length的結(jié)果是相同的玉凯,但不是等效的势腮,位運(yùn)算要快的多。這樣可以提升效率漫仆。
(2)在數(shù)組長(zhǎng)度h是2的冪次時(shí)候捎拯,散列的更加均勻。
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;
/**
* p = tab[i = (n - 1) & hash]這里就是散列操作盲厌,也就是用上數(shù)組長(zhǎng)度為2次冪的精髓所在署照,相當(dāng)于對(duì)數(shù)組長(zhǎng)度取余。
* 獲取這個(gè)位置的元素吗浩。
* 同時(shí)會(huì)知道這里的位置是鏈表還是紅黑樹(shù)建芙,后面插入會(huì)用上。
**/
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k)))) //如果key值相同那么下面不執(zhí)行懂扼,后面會(huì)用新的value覆蓋點(diǎn)舊的value
e = p;
else if (p instanceof TreeNode) //判斷節(jié)點(diǎn)是什么類型禁荸,如果是樹(shù)節(jié)點(diǎn)右蒲,就插入到紅黑樹(shù)中,不然就是鏈表中赶熟。
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;
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;
}
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 {
//初始化table數(shù)組瑰妄,就是一開(kāi)始什么都沒(méi)有的時(shí)候,初始化為默認(rèn)長(zhǎng)度16
newCap = DEFAULT_INITIAL_CAPACITY;
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;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
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);
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;
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;
}
get方法
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) {
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) //判斷是鏈表結(jié)構(gòu)還是紅黑樹(shù)結(jié)構(gòu)
return ((TreeNode<K,V>)first).getTreeNode(hash, key); //紅黑樹(shù)查找
do { //鏈表查找
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}