HashMap原始碼解讀

2021-09-26 19:03:18 字數 1748 閱讀 9637

public v put(k key, v value)

static final int hash(object key) 

final v putval(int hash, k key, v value, boolean onlyifabsent,

boolean evict)

//如果在遍歷鍊錶中途,發現可以值相等 則break; 替換value

if (e.hash == hash &&

((k = e.key) == key || (key != null && key.equals(k))))

break;

p = e;}}

//如果第乙個節點的key不相等而且沒有在遍歷到最後乙個節點就break

// 說明 e 就是 key 相等的那個節點 ,現在開始替換舊的value

v oldvalue = e.value;

if (!onlyifabsent || oldvalue == null)

e.value = value;

afternodeaccess(e);

return oldvalue;}}

++modcount;

//判斷是否需要擴容 大於門限值threshold 門限值等於(負載因子)*(容量)

if (++size > threshold)

resize();

afternodeinsertion(evict);

return null;

}

//負載因子 * 容量 > 元素數量 0.75 的數值

//resize() 的原始碼設計

final node resize()  //判斷oldcap的容量擴大兩倍 是否超過最大值  並且 是否大於等於預設的default_initial_capacity

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

//newthr == 0 則 根據負載因子算出門限值

if (newthr == 0)

threshold = newthr;

//建立新node[newcap]

@suppresswarnings()

node newtab = (node)new node[newcap];

table = newtab;

//把就的節點全部轉移到newtab上面去

//並且斷開舊節點的引用,方便gc

if (oldtab != null)

else

} while ((e = next) != null);

if (lotail != null)

if (hitail != null) }}

}}

return newtab;

}

//樹化 treeify  插入的節點都是紅的  不是紅的那麼就是黑的

HashMap原始碼解讀

一 建立乙個hashmap都做了哪些工作?mapmap new hashmap hahmap無參構造方法 public hashmap 可以看到設定了載入因子 預設0.75 閾值 預設容量16 預設載入因子0.75 12 table是hashmap內部資料儲存結構entry陣列。當hashmap的s...

HashMap原始碼解讀

今日閒來無事,擷取一段hashmap的 分析一下 int hash hash key 根據key 的hashcode 計算hash值 int i indexfor hash,table.length 根據hash值 計算出再陣列中的位置 for entrye table i e null e e.n...

HashMap原始碼解讀

hashmap原始碼分析 me 對集合檢視的迭代,hashmap的桶數加實際大小與時間成正比,也就是說,不可以把桶樹設定的太多或負載因子太小。o 對集合檢視的迭代需要與hashmap 例項的 容量 桶數 加上其大小 鍵值對映的數量 成比例的時間。因此,如果迭代效能很重要,則不要將初始容量設定得太高 ...