##Dictionary
public abstract class Dictionary
- Dictionary 类是任何可将键映射到相应值的类(如 Hashtable)的抽象父类。
- 任何非 null 对象都可以用作键或值。
- 此类已过时。新的实现应该实现 Map 接口,而不是扩展此类。
构造方法
public Dictionary() {}
定义了七个抽象方法,没有默认实现。
##Hashtable
public class Hashtable extends Dictionary implements Map, Cloneable, java.io.Serializable
- 实现一个哈希表,该哈希表将键映射到相应的值。
- 任何非 null 对象都可以用作键或值。
- 用作键的对象必须实现 hashCode 方法和 equals 方法。
- 有两个参数影响其性能:初始容量 和 加载因子。
成员变量
/**
* key-value以Entry形式存入此table中.
*/
private transient Entry[] table;
/**
* key-value对数.
*/
private transient int count;
/**
* 下一次扩容时的阀值
*/
private int threshold;
/**
* 加载因子
*/
private float loadFactor;
/**
* 修改次数
*/
private transient int modCount = 0;
常用方法
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;
}
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];
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;
}
由于Hashtable已不建议使用,故不多作源码阐述,从源码看出,Hashtable中很多方法是以synchronized修饰的,即同步的、线程安全的。
Hashtable与HashMap区别:
- Hashtable由synchronized实现线程安全,HashMap非线程安全。
- Hashtable不允许key或value为null,HashMap允许。
- Hashtable的enumerator迭代器不是fail-fast的,HashMap的迭代器(Iterator)是fail-fast迭代器。
- Hashtable继承自Dictionary,HashMap继承自AbstractMap。
- Hashtable有contains方法,HashMap因其效率低去掉了。
- Hashtable默认初始容量11,HashMap默认初始容量16。
- Hashtable扩容大小:oldCapacity * 2 + 1,HashMap扩容大小:oldCapacity * 2。