Hashtable和HashMap都是以key-value的形式管理和存储数据,但是两者还是在很多地方有些许差异。
首先是在对key和value的限制上,HashMap的key和value都可以为空,但是Hashtable的key和value都不能为空。这个可以从两者的put方法就可以看出端倪。
hashMap的put方法是
if (key == null)
return putForNullKey(value);//这里如果key为空,则另外处理,通篇没看到会因为value为空而put失败
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
接着是Hashtable的put方法
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}//这里value为空,则直接抛出异常,不予处理
// Makes sure the key is not already in the hashtable.
Entry tab[] = table;
int hash = key.hashCode();//这里如果key为空,则也抛出异常
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;
}
}
modCount++;
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
Entry<K,V> e = tab[index];
tab[index] = new Entry<K,V>(hash, key, value, e);
count++;
return null;
第二个差异的地方,就是HashMap没有线程安全,所有的方法都是public的属性,而对于Hashtable的方法来说,几乎每一个可以被用到的方法都添加了一个synchronized属性,这个属性意思就是同步,在任何时候,不能够同时被调用。虽然说在处理上,两者是几乎一致的,但是由于这个属性的存在,Hashtable在处理数据的性能上,特别是多线程访问的时候,没有HashMap快,但是同时,Hashtable则是线程安全的,而对于HashMap来说,则需要使用者自己去控制同步问题。
除了这两个地方之外,在方法列表上也有一些差异,Hashtable比hashMap多了一个contains方法,其实这个方法就是containsValue的意思,同时两者都有containsValue和containsKey这两个方法。
其他地方,两者几乎都是一致的。