第一:
HashMap可以存放一个键是null,多个值是null 的对象,而Hashtable则不可以存放键为null,或者是值为null的对象
第二:hashMap比hashtable出现的要迟
第三: HashMap是线程不安全的,即不可以让多个线程同时访问,Hashtable是线程安全的,可以让多个线程同时访问。
下面从源码上来看第一个区别的形成原因:
HashMap.class:
// 此处计算key的hash值时,会判断是否为null,如果是,则返回0,即key为null的键值对
// 的hash为0。因此一个hashmap对象只会存储一个key为null的键值对,因为它们的hash值都相同。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
// 将键值对放入table中时,不会校验value是否为null。因此一个hashmap对象可以存储
// 多个value为null的键值对
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
Hashtable.class:
public synchronized V put(K key, V value) {
// 确保value不为空。这句代码过滤掉了所有value为null的键值对。因此Hashtable不能
// 存储value为null的键值对
if (value == null) {
throw new NullPointerException();
}
// 确保key在table数组中尚未存在。
Entry<?,?> tab[] = table;
int hash = key.hashCode(); //在此处计算key的hash值,如果此处key为null,则直接抛出空指针异常。
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;
}