HashMap原始碼學習

2021-08-28 19:08:24 字數 2513 閱讀 5733

自己在學習的時候總感覺看懂了又沒有看懂,總有一層霧,所以乾脆寫個博文,看能不能徹底弄懂。

測試用**:

hashmapmap = new hashmap<>();

map.put("1","2");

map.put("2","4");

map.put("3","6");

map.put("4","8");

map.put("5","1");

map.put("6","1");

map.put("7","1");

map.put("8","1");

map.put("9","1");

map.put("10","1");

map.put("11","1");

map.put("12","3");

map.put("13","3");

put方法:

public v put(k key, v value) 

//hash(key)方法

static final int hash(object key)

putval方法:

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

boolean evict)

//鍊錶中hashcode都是相同的,如查詢到其中key值相等則退出迴圈

if (e.hash == hash &&

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

break;

//整個鍊錶遍歷完成後,不論是否轉成紅黑樹,e==null,如果鍊錶未遍歷完成即發現有相等值,則退出遍歷,下面進行替換

p = e;}}

//如果被替換節點e不為空,則進行值替換,並返回被替換下來的值

v oldvalue = e.value;

if (!onlyifabsent || oldvalue == null)

e.value = value;

afternodeaccess(e);

return oldvalue;}}

//每對hashmap進行一次操作就會進行一次自增。用來記錄該hashmap被操作的次數

++modcount;

//size就是我們實際使用中的大小,當新新增資料後超過了最大容量後,就需要進行一次擴容

if (++size > threshold)

//擴容

resize();

afternodeinsertion(evict);

return null;

}

resize()擴容方法:

final node resize() 

//這個是我們正常擴容所用的, 16《你翻倍後的容量<2的30次方 ,當你在這個區間時,將你的雜湊桶翻倍

else if ((newcap = oldcap << 1) < maximum_capacity &&

oldcap >= default_initial_capacity)

//普通翻倍操作

newthr = oldthr << 1; // double threshold

}//當new hashmap(4)的時候,是不符合上面的擴容範圍區間的,但是也需要擴容啊,於是,就進到下面了

// 此處也是第一次put的時候進入,因為非第一次的時候oldcap是不可能為0的,不會進入此處。

else if (oldthr > 0) // initial capacity was placed in threshold

newcap = oldthr;

else

//與上面new hashmap(4)的時候是一致的,當oldcap>0但是範圍又不在 16《翻倍後的容量<2的30次方 區間的時候,就來這裡了

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原始碼,所以再次認真學習整理一下 基於jdk1.7 hashmap主要由陣列和鍊錶組成,陣列是hashmap的主體,鍊錶是為了解決hash衝突而設計的。entry是hashmap的基本組成單元。每個entry包含一對key value的鍵值對。entry主要包括四個屬性...

HashMap原始碼學習

最大容量 2的30次方 static final int maximum capacity 1 30 預設的載入因子 static final float default load factor 0.75f 雜湊桶,存放鍊錶。長度是2的n次方,或者初始化時為0.transient node tabl...

HashMap原始碼學習筆記

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