本文主要記錄下自己學習hashmap
從構(gòu)造函數(shù)看
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);
}
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
主要邏輯其實就在這兩個函數(shù),其他都是弟弟
第一個構(gòu)造方法
initialCapacity:初始的容量
loadFactor:負載因子
重點是這個方法
tableSizeFor(initialCapacity);
這個方法主要是返回一個2的冪次方比的整書剛好比你給的整數(shù)大,也就是傳入12 返16。因為HashMap要求容量必須是2的冪。
threshold 不是resize的界限嗎?如果負載因子是0.75 返回的應該是12 現(xiàn)在確是16.
threshold 稍后會在put中重新定義
第二個構(gòu)造方法
重點邏輯
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
//獲取元素
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
//如果沒有talbe 重新建一個,根據(jù)插入的size 重新計算threshold
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
//如果已經(jīng)簡歷 ,但是小于傳進來的map,就需要擴容
else if (s > threshold)
resize();
//接著就是熟悉的便利插入元素
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
接下來再看上面的 resize()源碼
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
}
//table 為空,而oldThr 有數(shù)據(jù),還記得上面的構(gòu)造函數(shù)嗎,此時oldThr就代表的是容量且talbe 為null
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
//都沒有構(gòu)造過,就取默認值吧
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//新閾值為0 ,算一哈
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"})
//來個新talbe 放
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;
//若節(jié)點是單個節(jié)點
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
// 如果是treenode
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;
//一個長度為8的,在1位置上 一個1 一個9, 1的位置不變,9就加一個長度
do {
next = e.next;
//為0的不變
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
//為1的變化
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;
}
偷張圖

image.png
我們在看putVal的源碼
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, I;
//如果空的話resize
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//找到key值對應的槽并且是第一個,直接加入
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 {
//沒找到一樣的,加在最后,同時判斷是否轉(zhuǎn)樹
for (int binCount = 0; ; ++binCount) {
//如果一直為空,加在最后
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//超過了設置長度8就轉(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;
}
}
//如果e不為空就替換舊的oldValue值
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;
}