Hashtable 原始碼解析

2021-09-25 18:43:04 字數 1577 閱讀 4380

hashtable 底層是以陣列加鍊表實現的,是執行緒安全。

private transient entry<?,?> table;//全域性變數,存放hashtable的資料

private float loadfactor;//全域性變數,負載因子

public hashtable()

// 帶初始化數

public hashtable(int initialcapacity, float loadfactor)

public synchronized v put(k key, v value)

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

entry<?,?> tab = table; //把table的值賦值給tab  陣列

int hash = key.hashcode();//獲取key值得hashcode

int index = (hash & 0x7fffffff) % tab.length;   //獲取hash表的index值

@suppresswarnings("unchecked")

entryentry = (entry)tab[index];

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

}addentry(hash, key, value, index);//  往hashtable中新增新的元素

return null;

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

// creates the new entry.

@suppresswarnings("unchecked")

entrye = (entry) tab[index];//獲取當前元素要插入陣列位置的值

tab[index] = new entry<>(hash, key, value, e);//建立新的元素,插入到陣列的第乙個位置,若該陣列已存在,則把插入元

//素指向的下乙個元素為已存在的素組鍊錶

count++;

}//對hashtable進行擴容

@suppresswarnings("unchecked")

protected void rehash()

entry<?,?> newmap = new entry<?,?>[newcapacity];//建立新的hashtable

modcount++;

threshold = (int)math.min(newcapacity * loadfactor, max_array_size + 1);// 修改閾值

table = newmap;//把新建立的陣列賦值給table

//把舊的hashtable在擴容後重新排列

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

@suppresswarnings("unchecked")

public synchronized v get(object key)

}return null;

}

HashTable 原始碼解析 jdk1 8

hashtable採用桶位 鍊錶結構實現,如下圖所示 底層是乙個儲存entry的陣列 private transient entry,table 乙個單向鍊錶結構 private static class entryimplements map.entry suppresswarnings unch...

原始碼剖析 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 ...