首先他们的相同点都实现了Map接口,不同点有很多:
1. Hashtable 继续了抽象类Dictionary,所有Hashtable是线程安全的,而HashMap不是
2. Hashtable不能存放key为null的对象,它会抛出异常,而HashMap是可以的。
3. 初始化数组大小不一样,HashMap是16,而Hashtable是11
4. 扩容机制也不同,HashMap是旧的大小×2,而Hashtable是旧的大小×2+1
5. 计算数组下标index的方法不同:
Hashtable的如下
HashMap的如下
1. Hashtable 继续了抽象类Dictionary,所有Hashtable是线程安全的,而HashMap不是
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable {
2. Hashtable不能存放key为null的对象,它会抛出异常,而HashMap是可以的。
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;
for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
V old = e.value;
e.value = value;
return old;
}
}
3. 初始化数组大小不一样,HashMap是16,而Hashtable是11
public Hashtable() {
this(11, 0.75f);
}
4. 扩容机制也不同,HashMap是旧的大小×2,而Hashtable是旧的大小×2+1
protected void rehash() {
int oldCapacity = table.length;
Entry[] oldMap = table;
int newCapacity = oldCapacity * 2 + 1;
Entry[] newMap = new Entry[newCapacity];
modCount++;
threshold = (int)(newCapacity * loadFactor);
table = newMap;
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry<K,V> old = oldMap[i] ; old != null ; ) {
Entry<K,V> e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = newMap[index];
newMap[index] = e;
}
}
}
5. 计算数组下标index的方法不同:
Hashtable的如下
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
HashMap的如下
/**
* 计算hashCode的方法
*/
static int hash(int h) {
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
/**
* 根据hashcode和数组的大小来计算数组下标的方法
*/
static int indexFor(int h, int length) {
return h & (length-1);
}