1、構造方法
1public
hashmap() 45
public hashmap(int
initialcapacity) 89
public hashmap(int initialcapacity, float
loadfactor)
2324
public hashmap(map<? extends k, ? extends v>m)
4種構造方法
1、無參的構造方法,也就是我們最常用的構造方法,他給我們的預設的初始化 容量是16 也就是entry陣列是16 ,entry 有什麼引數?
一共4個引數,key, value ,hash ,還有乙個就是entrynext 物件中的物件,負載因子預設是0.75
2、給乙個陣列大小的引數的是第二個建構函式
3、給兩個的是上面所說的兩個引數的建構函式,內容就是檢驗入參,最後的是初始化鍊錶,這裡是個空的方法,為的是子類要可以重寫方法
put方法
//入參是key和value
public
v put(k key, v value)
如果key 為空返回下面的方法。作用:
if (key == null
)
return
putfornullkey(value);
int hash =hash(key);
int i =indexfor(hash, table.length);
for (entrye = table[i]; e != null; e =e.next)
}modcount++;
addentry(hash, key, value, i);
return
null
; }
/*** inflates the table.
*/private
void inflatetable(int
tosize)
//入參是插入進來的value
private
v putfornullkey(v value)
}陣列變更次數加一
modcount++;
設定hash值為零,key值為null value為入參的值
addentry(0, null, value, 0);
return
null
;void addentry(int hash, k key, v value, int
bucketindex)
入參是原來長度的2被
void resize(int
newcapacity)
新建乙個這麼大的陣列,
entry newtable = new
entry[newcapacity];
把老的陣列中的數轉換到新陣列中
transfer(newtable, inithashseedasneeded(newcapacity));
table =newtable;
threshold = (int)math.min(newcapacity * loadfactor, maximum_capacity + 1);
}void transfer(entry newtable, boolean
rehash) 重置這個hash值,與運算,也就是獲取乙個位置,放到先新的陣列中的位置
int i =indexfor(e.hash, newcapacity);
e.next =newtable[i];
newtable[i] =e;
e =next;}}
}
HashMap原始碼解析
以jdk1.8為例,hashmap是乙個用於儲存key value鍵值對的集合,每乙個鍵值對是乙個node jdk1.7叫做entry 後台是用乙個node陣列來存放資料,這個node陣列就是hashmap的主幹。這裡我們主要來分析hashmap的get和put方法。public v put k k...
hashMap 原始碼解析
這幾天跳槽 被人問得最多的問題就是基礎方面的知識.當時學習的時候有點囫圇吞棗.現在回頭把這些基本的集合類原始碼都仔細閱讀下 hashmap 用的是最頻繁的.所以問得也最多了.initcapacity 初始化的容量 loadfacotr 負載因子 主要用來計算threshold的值 threshold...
HashMap原始碼解析
預設字段 static final int default initial capacity 1 4 預設node的陣列長度 16 static final int maximum capacity 1 30 陣列的最大長度 2 30 static final float default load ...