概述java
與 HashMap 相似,Hashtable 也是散列表的實現。它的內部結構能夠理解爲「數組 + 鏈表」的形式,結構示意圖以下:數組
Hashtable 的類繼承結構與簽名以下:安全
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable {}
併發
Hashtable 的 key 和 value 都不能爲空(HashMap 的 key 和 value 都容許爲空),而且 key 必需要實現 hashCode 方法和 equals 方法。app
PS: Hashtable 目前使用不是不少,若無線程安全的需求,推薦使用 HashMap;若須要線程安全的高併發實現,推薦使用 ConcurrentHashMap。高併發
代碼分析源碼分析
Entry 類flex
private static class Entry<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Entry<K,V> next;
protected Entry(int hash, K key, V value, Entry<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&
(value==null ? e.getValue()==null : value.equals(e.getValue()));
}
public int hashCode() {
return hash ^ Objects.hashCode(value);
}
// ...
}
ui
Entry 類實現了 Map.Entry 接口,是 Hashtable 中的節點類。this
成員變量
// Hashtable 內部存儲元素的數組
private transient Entry<?,?>[] table;
// Hashtable 的閾值 (int)(capacity * loadFactor)
private int threshold;
// 負載因子
private float loadFactor;
// 數組可以分配的最大容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
構造器
// 構造一個空的 Hashtable,初始容量爲 11,負載因子爲 0.75
public Hashtable() {
this(11, 0.75f);
}
// 構造一個空的 Hashtable,指定初始容量,負載因子爲 0.75
public Hashtable(int initialCapacity) {
this(initialCapacity, 0.75f);
}
// 構造一個空的 Hashtable,指定初始容量和負載因子
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);
}
// 使用給定的 Map 構造一個 Hashtable
public Hashtable(Map<? extends K, ? extends V> t) {
this(Math.max(2*t.size(), 11), 0.75f);
putAll(t);
}
主要方法分析
put 方法
public synchronized V put(K key, V value) {
// Make sure the value is not null (value 不能爲空)
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
// 計算 key 在 table 中的索引
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
// 判斷 key 在 table 中是否已存在,若存在,則用 value 替換舊值
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
// 若不存在,則執行 addEntry 方法,將 key-value 添加到 table
addEntry(hash, key, value, index);
return null;
}
能夠看到,key 或 value 有一個爲空都會拋出 NullPointerException 異常,所以兩者都不能爲空。
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 = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
// 將 key-value 添加到 table 中(頭插法,即插到鏈表的頭部)
// 即:先拿到 index 位置的元素,若爲空,表示插入 entry 後則只有一個元素;
// 若不爲空,表示該位置已有元素,將已有元素 e 鏈接到新的 entry 後面
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) tab[index];
tab[index] = new Entry<>(hash, key, value, e);
count++;
}
擴容操做 rehash() 以下:
protected void rehash() {
int oldCapacity = table.length;
Entry<?,?>[] oldMap = table;
// overflow-conscious code
// 新容量爲舊容量的 2 倍加 1
int newCapacity = (oldCapacity << 1) + 1;
// 若新容量的值超過最大容量 MAX_ARRAY_SIZE,且舊容量爲 MAX_ARRAY_SIZE,則直接返回;
// 若舊容量值不爲 MAX_ARRAY_SIZE,則新容量爲 MAX_ARRAY_SIZE.
if (newCapacity - MAX_ARRAY_SIZE > 0) {
if (oldCapacity == MAX_ARRAY_SIZE)
// Keep running with MAX_ARRAY_SIZE buckets
return;
newCapacity = MAX_ARRAY_SIZE;
}
// 新建一個 Entry 數組,容量爲上面計算的容量大小
Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];
modCount++;
threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
table = newMap;
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;
}
}
}
擴容操做,若 index 位置爲鏈表,且插入順序爲 一、二、3,則在該位置的存儲順序爲 三、二、1。擴容時,會從前日後讀取元素並操做,所以擴容後的順序爲 三、二、1。示意圖:
值得注意的是,put 方法(包括後面分析的 get 和 remove 等方法)帶有 synchronized 關鍵字,Hashtable 就是經過這種方式實現線程安全的。這裏鎖定的是整個 table,所以併發效率較低,這也是高併發場景下推薦使用 ConcurrentHashMap 的緣由。
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;
}
分析過 put 方法後,get 方法和 remove 方法分析起來就比較簡單了,它們和 put 方法相似。
remove 方法
public synchronized V remove(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>)tab[index];
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;
}
三種集合視圖 EntrySet、keySet 和 values 分別以下:
private transient volatile Set<K> keySet;
private transient volatile Set<Map.Entry<K,V>> entrySet;
private transient volatile Collection<V> values;
public Set<K> keySet() {
if (keySet == null)
keySet = Collections.synchronizedSet(new KeySet(), this);
return keySet;
}
public Set<Map.Entry<K,V>> entrySet() {
if (entrySet==null)
entrySet = Collections.synchronizedSet(new EntrySet(), this);
return entrySet;
}
public Collection<V> values() {
if (values==null)
values = Collections.synchronizedCollection(new ValueCollection(),
this);
return values;
}
小結
1. Hashtable 是散列表的實現,處理散列衝突使用的是鏈表法,內部結構能夠理解爲「數組 + 鏈表」;
2. 默認初始化容量爲 11,默認負載因子爲 0.75;
3. 線程安全,使用 synchronized 關鍵字,併發效率低;
4. 若無需保證線程安全,推薦使用 HashMap;若須要線程安全的高併發場景,推薦使用 ConcurrentHashMap。
相關閱讀:
Stay hungry, stay foolish.