HashTable 原始碼解析 jdk1 8

2021-10-09 08:20:41 字數 2928 閱讀 7754

hashtable採用桶位+鍊錶結構實現,如下圖所示:

底層是乙個儲存entry的陣列

private transient entry,?> table;
乙個單向鍊錶結構

private static class entryimplements map.entry

@suppresswarnings("unchecked")

protected object clone()

// map.entry ops

public k getkey()

public v getvalue()

public v setvalue(v value)

public boolean equals(object o)

public int hashcode()

public string tostring()

}

//記錄了儲存的元素數量

private transient int count;

//元素數量超過這個值後,會執行陣列擴容

private int threshold;

//負載因子

private float loadfactor;

預設構造方法,構造乙個大小為11,負載因子為0.75的hashtable

public hashtable()
注意key和value都不能為空

//hashtable之所以是執行緒安全的,就是因為在put和get方法上使用了synchronized關鍵字進行修飾

public synchronized v put(k key, v value)

// makes sure the key is not already in the hashtable.

entry,?> tab = table;

//因為直接使用key.hashcode(),而沒有像hashmap一樣判斷key是否是null,所以key為null時,呼叫key.hashcode()會出錯,所以key也不能為空

int hash = key.hashcode();

//定址的方式是取餘

int index = (hash & 0x7fffffff) % tab.length;

@suppresswarnings("unchecked")

entryentry = (entry)tab[index];

for(; entry != null ; entry = entry.next)

}//如果table[index]所連線的鍊錶上不存在相同的key,則通過addentry() 方法將新結點載入到鍊錶的開頭

addentry(hash, key, value, index);

return null;

}

private void addentry(int hash, k key, v value, int index) 

//將新結點放在原結點前,相當於把新結點放在table[index]位置,即整個鍊錶的首部

@suppresswarnings("unchecked")

entrye = (entry) tab[index];

tab[index] = new entry<>(hash, key, value, e);

count++;

}

3.2.1.1 rehash

增加陣列容量,並重新調整整個hashtable。

@suppresswarnings("unchecked")

protected void rehash()

entry,?> newmap = new entry,?>[newcapacity];

modcount++;

threshold = (int)math.min(newcapacity * loadfactor, max_array_size + 1);

table = newmap;

for (int i = oldcapacity ; i-- > 0 ;) }}

如果存在鍵值對,那麼返回key對應的值,否則返回null,返回的比較結果是通過equals返回的。

@suppresswarnings("unchecked")

//hashtable執行緒安全的願意,synchronized關鍵字

public synchronized v get(object key)

}return null;

}

hashmap中key和value均可以為null,但是hashtable中key和value均不能為null。

hashmap採用的是陣列(桶位)+鍊錶+紅黑樹結構實現,而hashtable中採用的是陣列(桶位)+鍊錶實現。

hashmap**現hash衝突時,如果鍊錶節點數小於8時是將新元素加入到鍊錶的末尾,而hashtable**現hash衝突時採用的是將新元素加入到鍊錶的開頭。

hashmap中陣列容量的大小要求是2的n次方,如果初始化時不符合要求會進行調整,而hashtable中陣列容量的大小可以為任意正整數。

hashmap中的定址方法採用的是位運算按位與,而hashtable中定址方式採用的是求餘數。

hashmap不是執行緒安全的,而hashtable是執行緒安全的,hashtable中的get和put方法均採用了synchronized關鍵字進行了方法同步。

hashmap中預設容量的大小是16,而hashtable中預設陣列容量是11。

Hashtable 原始碼解析

hashtable 底層是以陣列加鍊表實現的,是執行緒安全。private transient entry table 全域性變數,存放hashtable的資料 private float loadfactor 全域性變數,負載因子 public hashtable 帶初始化數 public has...

原始碼剖析 Hashtable 原始碼剖析

hashtable同樣是基於雜湊表實現的,同樣每個元素都是key value對,其內部也是通過單鏈表解決衝突問題,容量不足 超過了閾值 時,同樣會自動增長。hashtable也是jdk1.0引入的類,是執行緒安全的,能用於多執行緒環境中。hashtable同樣實現了serializable介面,它支...

Hashtable原始碼詳解

成員變數private transient entry table 儲存鍊錶的陣列 private transient int count private int threshold private float loadfactor private transient int modcount 0 ...