HashMap原始碼筆記

2021-10-01 07:41:14 字數 2922 閱讀 8682

//預設的初始化容量為16 

static

final

int default_initial_capacity =

1<<4;

//最大的容量,容量的值必須是2的冪並且小於最大的容量,最大值為2的30次方

static

final

int maximum_capacity =

1<<30;

//載入因子預設值為0.75

static

final

float default_load_factor =

0.75f

;//計數閾值,超過這個值將會使用樹形結構替代鍊錶結構

static

final

int treeify_threshold =8;

//由樹形結構轉換成鍊錶的閾值

static

final

int untreeify_threshold =6;

//樹形結構最小的容量為64

static

final

int min_treeify_capacity =64;

//鍊錶陣列

transient node

table;

//hashmap中value的集合

transient set

> entryset;

//hashmap的長度

transient

int size;

//調整大小的下乙個大小值,閾值

int threshold;

//hashtable的載入因子

final

float loadfactor;

public v get

(object key)

/** * implements map.get and related methods

** @param hash hash for key

* @param key the key

* @return the node, or null if none

*/final node

getnode

(int hash, object key)

while

((e = e.next)

!= null);}

}return null;

}

public v put

(k key, v value)

/** * implements map.put and related methods

** @param hash hash for key

* @param key the key

* @param value the value to put

* @param onlyifabsent if true, don't change existing value

* @param evict if false, the table is in creation mode.

* @return previous value, or null if none

*/final v putval

(int hash, k key, v value,

boolean onlyifabsent,

boolean evict)

if(e.hash == hash &&

((k = e.key)

== key ||

(key != null && key.

equals

(k))))

break

; p = e;}}

// 如果存在相同的key 覆蓋舊值

if(e != null)

}++modcount;

//超過最大容量,擴容if(

-resize方法

final node

resize()

elseif(

(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

if(newthr ==0)

threshold = newthr;

@suppresswarnings()

node

newtab =

(node

)new

node

[newcap]

; table = newtab;

if(oldtab != null)

else

}while

((e = next)

!= null);if

(lotail != null)

if(hitail != null)}}

}}return newtab;

}

HashMap原始碼學習筆記

hashmap的底層主要是基於陣列和鍊錶來實現的,它之所以有相當快的查詢速度主要是因為它是通過計算雜湊碼來決定儲存的位置。hashmap中主要是通過key的hashcode來計算hash值的,只要hashcode相同,計算出來的hash值就一樣。如果儲存的物件對多了,就有可能不同的物件所算出來的ha...

HashMap原始碼學習筆記

hashmap 資料結構 初始容量 static final int de t initial capacity 1 4 最大容量 static final int maxinum capacity 1 30 擴容因子 static final float default load factor 0...

學習筆記HashMap原始碼學習

hashmap hashmapextends abstractmap implements map,cloneable,serializable 繼承abstractmap類,實現頂層介面map介面 int default initial capacity 1 4 預設容量為16 int maxim...