HashMap 優化% 使用&運算 來實現取模
阿新 • • 發佈:2022-04-15
1.前提條件 值必須是2的冪次方,看java1.8 hashMap原始碼
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;
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))))
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;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
2.找到程式碼 if ((p = tab[i = (n - 1) & hash]) == null) n必須是2的倍數
首先是hash這個值,轉成二進位制,就是0和1,我們先用個例子來說明下,n=4,hash=13
13的二進位制是1101
4的二進位制是 0100
高位1100 完全可以整除100 所以高位捨棄 得到0001 現在只需要考慮怎麼得到0001這個值
那麼用 (4-1)& 0001 (0011)&0001 得到 0001
得到公式(n-1)&hash = = hash%n