Hashtable類簡介
java version "1.7.0_67"
Hashtable類繼承了Dictionary抽象類,實現了Map、Cloneable、java.io.Serializable接口,它的底層實現原理和HashMap類是差不多的。Hashtable類最大的一個特點是:線程安全的,對外提供調用的方法都加了同步關鍵字Synchronized,但同時也降低了性能。插入的“鍵—值”都不能爲null。
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable {
1.常用的構造方法HashTable(),默認初始化容量大小11,加載因子0.75
/**
* Constructs a new, empty hashtable with a default initial capacity (11)
* and load factor (0.75).
*/
public Hashtable() {
this(11, 0.75f);
}
2.HasTable中的put(K key, V value)方法,用了synchronized關鍵字保證線程安全
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
//在HashTable中value不能爲null,否則報空指針異常
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry tab[] = table;
int hash = hash(key);//key爲null則會報空指針異常錯誤
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
//哈希碼值相等並且key值也相等,就會把就的value值替換成新的value值
if ((e.hash == hash) && e.key.equals(key)) {
V old = e.value;
e.value = value;
return old;
}
}
modCount++;
//總數量大於等於閥值,那麼就需要對數組進行擴容
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
hash = hash(key);
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
Entry<K,V> e = tab[index];
//根據索引index處存入新的entry,並且把有一個next引用指向舊的entry
//連着成一個鏈表,新插入的都是成爲新的鏈表頭
tab[index] = new Entry<>(hash, key, value, e);
count++;
return null;
}
可以看出hash(Object k)方法,計算哈希碼值比較的簡單,沒有像HashMap中的那樣做防碰撞處理。
private int hash(Object k) {
// hashSeed will be zero if alternative hashing is disabled.
return hashSeed ^ k.hashCode();
}
3.Hashtable 類中的內部類:Enumerator<T>,實現了接口Enumeration<T>和Iterator<T>,主要的用途是對外提供迭代器和枚舉器用於遍歷Hashtable中的key和value值。
總結:
當前,Hashtable在實際應用中不常用了,多線程訪問下被ConcurrentHashMap類所替代了,因爲它的性能比Hashtable高。