jdk1.8 核心參數(shù):
HashMap 初始容量
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
hashMap 最大容量
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
hashmap加載因子 提前擴(kuò)容
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
鏈表長度大于8的時(shí)候,將鏈表轉(zhuǎn)為紅黑數(shù)
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
紅黑樹長度小于6的時(shí)候轉(zhuǎn)換為鏈表
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
(數(shù)組容量>=64&鏈表長度大于8)鏈表轉(zhuǎn)紅黑樹
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
*/
static final int MIN_TREEIFY_CAPACITY = 64;
底層采用單向鏈表
/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
final int hash;
final K key;
V value;
Node<K,V> next;
將key的hash 保存起來是為了下次擴(kuò)容的時(shí)候能夠計(jì)算該key在新的table中index的值丰滑。
table數(shù)組 類型: 單向鏈表
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
transient 不能被序列化
遍歷hashmap集合的時(shí)候防止被篡改
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
transient int modCount;
加載因子
/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor;
hashmap put 方法底層實(shí)現(xiàn)顾犹;
n=table數(shù)組的長度 index=key 存放在那個(gè)index下標(biāo)位置。tab 和p臨時(shí)table大小接收褒墨。
- Node<K,V>[] tab; Node<K,V> p; int n, i;
2炫刷,將全局table=tab 判斷是否為空,如果為空的情況下或者長度為0 開始對(duì)table實(shí)現(xiàn)擴(kuò)容貌亭。
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;//懶加載默認(rèn)擴(kuò)容大小為16
3,計(jì)算key index的值判斷是否有發(fā)生index沖突柬唯,如果沒有發(fā)生index沖突
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
獲取原來的table長度為0;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
0 hashmap 下一次提前擴(kuò)容的大小
int oldThr = threshold;
記錄新的table容量圃庭,新下一次擴(kuò)容的大小锄奢。
int newCap, newThr = 0;
存放index下標(biāo)的位置
4失晴, tab[i] = newNode(hash, key, value, null);
5,##如果hash值相同且equals也相同就覆蓋值
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
將新的value覆蓋給老的value
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
遍歷鏈表拘央,如果鏈表為空的情況下涂屁,直接追加在next后面。
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果鏈表長度大于8且長度>64直接轉(zhuǎn)為紅黑樹
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//查找鏈表中是否包含key如果存在key直接修改value
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
modcount++ HashMap結(jié)果集 集合線程不安全
A 線程 遍歷 hashmap結(jié)果集 B線程向hashMap 存放key
modCount 新增++fastclass機(jī)制
java.util.HashMap 不是線程安全的灰伟,因此如果在使用迭代器的過程中有其他線程修改了map拆又,那么將拋出ConcurrentModificationException,這就是所謂fail-fast策略栏账。這一策略在源碼中的實(shí)現(xiàn)是通過 modCount 域帖族,modCount 顧名思義就是修改次數(shù),對(duì)HashMap 內(nèi)容的修改都將增加這個(gè)值挡爵,那么在迭代器初始化過程中會(huì)將這個(gè)值賦給迭代器的 expectedModCount竖般。在迭代過程中,判斷 modCount 跟 expectedModCount 是否相等茶鹃,如果不相等就表示已經(jīng)有其他線程修改了 Map:
package com.taotao.hashmap001;
import java.util.HashMap;
/**
*@author tom
*Date 2020/9/24 0024 8:09
*
*/
public class Test11 {
public static void main(String[] args) {
HashMap<Object,String> hashmap=new HashMap<>();
for (int i = 0; i < 12; i++) {
hashmap.put(i,i+"");
}
hashmap.forEach((k,v)->{
hashmap.put(13,13+"");
System.out.println(k+","+v);
});
}
}
api\1.7.30\slf4j-api-1.7.30.jar" com.taotao.hashmap001.Test11
0,0
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap.forEach(HashMap.java:1291)
at com.taotao.hashmap001.Test11.main(Test11.java:16)
Process finished with exit code 1
遍歷hashmap的時(shí)候改變了hashmap 的長度 所以 報(bào)錯(cuò) modCount
public void forEach(BiConsumer<? super K, ? super V> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key, e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
擴(kuò)容:
HashMap7擴(kuò)容產(chǎn)生死循環(huán)問題
oid transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
HashMap1.7 擴(kuò)容 16*2=32
hashmap1.8 擴(kuò)容 16<<1 位移
擴(kuò)容的時(shí)候原來的tablekey 轉(zhuǎn)移到新的table 數(shù)組中
重新計(jì)算時(shí)候 has 值不變 node節(jié)點(diǎn)中保存計(jì)算好hash值涣雕。只是改變下標(biāo)
誤區(qū):沒有重新計(jì)算hash值
異或運(yùn)算^無符號(hào)右移>>>&與運(yùn)算
1.<<(向左位移) 針對(duì)二進(jìn)制,轉(zhuǎn)換成二進(jìn)制后向左移動(dòng)2位闭翩,后面用0補(bǔ)齊
10的二進(jìn)制1010
0000 0000 0000 0000 0000 0000 0000 1010 ---32位
0000 0000 0000 0000 0000 0000 0010 1000
System.out.println(10 << 2);//1010 =40
2.>>(向右位移) 針對(duì)二進(jìn)制挣郭,轉(zhuǎn)換成二進(jìn)制后向右移動(dòng)2位,操作數(shù)移除右邊界的位被屏蔽 正數(shù)高位
補(bǔ)0 負(fù)數(shù)補(bǔ)1
10的二進(jìn)制1010
0000 0000 0000 0000 0000 0000 0000 1010
System.out.println(10 >> 2);//10=2
3.>>>(不帶符號(hào)右移) 針對(duì)二進(jìn)制疗韵,轉(zhuǎn)換成二進(jìn)制后向右移動(dòng)2位兑障,操作數(shù)移除右邊界的位被屏蔽
正數(shù)高位 補(bǔ)0 負(fù)數(shù)補(bǔ)0
異或運(yùn)算^ 針對(duì)二進(jìn)制,相同的為0蕉汪,不同的為1
0010 --2
0011 --3
0001 --1
4.&(與運(yùn)算) 針對(duì)二進(jìn)制旺垒,00的0 11的1 10 的0
0010--2
0011--3
0010--2
HashMap如何降低Hash沖突概率
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
((p = tab[i = (n - 1) & hash])
1、保證不會(huì)發(fā)生數(shù)組越界
首先我們要知道的是肤无,在HashMap,數(shù)組的長度按規(guī)定一定是2的冪骇钦。因此宛渐,數(shù)組的長度的二進(jìn)制形式是:10000…000, 1后面有偶數(shù)個(gè)0。 那么眯搭,length - 1 的二進(jìn)制形式就是01111.111, 0后面有偶數(shù)個(gè)1窥翩。最高位是0, 和hash值相“與”,結(jié)果值一定不會(huì)比數(shù)組的長度值大鳞仙,因此也就不會(huì)發(fā)生數(shù)組越界寇蚊。一個(gè)哈希值是8,二進(jìn)制是1000棍好,一個(gè)哈希值是9仗岸,二進(jìn)制是1001允耿。和1111“與”運(yùn)算后,結(jié)果分別是1000和1001扒怖,它們被分配在了數(shù)組的不同位置较锡,這樣,哈希的分布非常均勻盗痒。
HashMap8擴(kuò)容底層原理
將原來的鏈表拆分兩個(gè)鏈表存放蚂蕴; 低位還是存放原來index位置 高位存放index=j+原來長度
if ((e.hash & oldCap) == 0) { 由于oldCap原來的容量沒有減去1 所以所有的hash&oldCap
為0或者1;
HashMap加載因子為什么是0.75而不是1或者0.5
產(chǎn)生背景:減少Hash沖突index的概率俯邓;
查詢效率與空間問題骡楼;
簡單推斷的情況下,提前做擴(kuò)容:
1.如果加載因子越大稽鞭,空間利用率比較高鸟整,有可能沖突概率越大;
2.如果加載因子越小川慌,有可能沖突概率比較小吃嘿,空間利用率不高;
空間和時(shí)間上平衡點(diǎn):0.75
統(tǒng)計(jì)學(xué)概率:泊松分布是統(tǒng)計(jì)學(xué)和概率學(xué)常見的離散概率分布
HashMap如何存放1萬條key效率最高
(需要存儲(chǔ)的元素個(gè)數(shù) / 負(fù)載因子) + 1
10000/0.75+1=13334
正常如果存放1萬個(gè)key的情況下 大概擴(kuò)容10次=16384