HashMap原始碼詳解

2021-08-22 00:13:11 字數 2484 閱讀 9295

成員變數

static

final

int default_initial_capacity = 1

<< 4; // aka 16

static

final

int maximum_capacity = 1

<< 30;// aka 2^30

static

final

float default_load_factor = 0.75f;

static

final

int treeify_threshold = 8;

static

final

int untreeify_threshold = 6;

static

final

int min_treeify_capacity = 64;

/* filed */

transient node table;//table為node鍊錶構建的陣列

transient set> entryset;

transient

int size;

transient

int modcount;

int threshold;

final

float loadfactor;//負載因子,預設值為0.75

//靜態內部類

static class nodeimplements map.entry

}

構造方法初始化
public

hashmap(int initialcapacity, float loadfactor)

public

hashmap(int initialcapacity)

public

hashmap()

put方法
public v put(k key, v value) 

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;}}

v oldvalue = e.value;

if (!onlyifabsent || oldvalue == null)

e.value = value;

afternodeaccess(e);

return oldvalue;}}

++modcount;

// 超過load factor*current capacity,resize

if (++size > threshold)

resize();

afternodeinsertion(evict);

return

null;

}final node resize()

// 沒超過最大值,就擴充為原來的2倍

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

// 計算新的resize上限

if (newthr == 0)

threshold = newthr;

@suppresswarnings()

node newtab = (node)new node[newcap];//建立table陣列

table = newtab;

if (oldtab != null)

// 原索引+oldcap

else

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

// 原索引放到bucket裡

if (lotail != null)

// 原索引+oldcap放到bucket裡

if (hitail != null) }}

}}

return newtab;

}

get方法
public v get(object key) 

final nodegetnode(int hash, object key) while ((e = e.next) != null);}}

return

null;

}

HashMap原始碼系列 HashMap的屬性

public class hashmap extends abstractmap implements map,cloneable,serializable容載因子 容載因子越大,table陣列中儲存的資料越密集,碰撞的可能性就越大。容載因子越小,儲存越稀疏,碰撞的可能性就越小,不過浪費儲存空間。轉...

HashMap原始碼解讀

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

HashMap原始碼分析

public hashmap int initialcapacity,float loadfactor 2 接下來是重要的put方法,put方法用於將鍵值對儲存到map中,讓我們來具體分析一下。public v put k key,v value if key null 若key為null,則將va...