《Java1.8源碼分析》:HashTable
繼承結構
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable
繼承的是Dictionary類,實現了Map、Cloneable、Serializable。
注意:這也是Hashtable和HashMap第一個不同的地方,HashMap實現的是AbstractMap類。
屬性
// 用來實現Hashtable所藉助的數組,默認大小爲11.(HashMap默認是16,且是2的冪次方)
1. private transient Entry<?,?>[] table;
//用來記錄table數組中存儲元素的個數
2. private transient int count;
//擴容的門限,即如果數組table中存儲的元素個數大於threshold,則擴大數組table的大小
3. private int threshold;
//加載因子,默認值爲0.75f,擴容門線threshold的值等於loadFactor與數組table的容量的乘積.
4. private float loadFactor;
構造函數
//hashTable有4個構造函數,但都是調用這個
public Hashtable(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load: "+loadFactor);
if (initialCapacity==0)
initialCapacity = 1;
this.loadFactor = loadFactor;
table = new Entry<?,?>[initialCapacity];
threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
}
put函數
//hashtable是安全的,每個方法都加了鎖
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
//如果數組table中有值,則檢查下是否有此key,如果有,則更新value
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
addEntry(hash, key, value, index);
return null;
}
從源碼中可以看到,put方法首先檢查value是否爲null,如果爲空,則拋異常。
注意:這也是Hashtable與HashMap的另一個不同點,在HashMap中,null可以作爲鍵,這樣的鍵只有一個;可以有一個或多個鍵所對應的值爲null。
addEntry函數
給數組table的index位置添加元素。
private void addEntry(int hash, K key, V value, int index) {
modCount++;
Entry<?,?> tab[] = table;
//檢查是否擴容
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
//需要重新計算hash值
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
@SuppressWarnings("unchecked")
//獲取table數組在index的元素,如果非空,則新節點放在這個節點的前面,成爲新的鏈表頭
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
}
思想:首先檢查下數組table存儲的元素個數是否大於擴容門限threshold.如果大於,則擴容,擴容之後,重新獲取key的hashcode,並根據hashcode重新計算要存儲的位置index.最後將要存儲的數據存儲到table[index]中。這裏要注意的一點是,如果table[index]中已經有其它元素了,那麼在同一個位子上的元素將以鏈表的形式存放,新加入的放在鏈頭,最先加入的放在鏈尾
rehash函數
rehash方法的實現思想如下:首先對原來的長度乘以2+1就爲即將擴容的長度。然後新建一個newCapacity的數組,將原來的table數組的元素拷貝到新的數組中去即可。
protected void rehash() {
int oldCapacity = table.length;
Entry<?,?>[] oldMap = table;
// overflow-conscious code
//擴容後數組爲2*n+1
int newCapacity = (oldCapacity << 1) + 1;
if (newCapacity - MAX_ARRAY_SIZE > 0) {
if (oldCapacity == MAX_ARRAY_SIZE)
// Keep running with MAX_ARRAY_SIZE buckets
return;
newCapacity = MAX_ARRAY_SIZE;
}
Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];
modCount++;
//設置新閾值
threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
table = newMap;
//將原數據拷貝到新hashTable中
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
Entry<K,V> e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = (Entry<K,V>)newMap[index];
newMap[index] = e;
}
}
}
get函數
public synchronized V get(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
return (V)e.value;
}
}
return null;
}
remove函數
public synchronized V remove(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
//先根據hash值找到數組
Entry<K,V> e = (Entry<K,V>)tab[index];
//遍歷Entry,找到key
for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
count--;
V oldValue = e.value;
e.value = null;
return oldValue;
}
}
return null;
}
小結
hashTable底層也是基於數組實現的,對外的每個方法都加了synchrronized進行同步。