上一篇讲到了HashMap,这一篇来讲一下HashTable。
其实两者区别不是很大,HashTable出现的比较早,继承的是Dictionary,Dictionary是一个抽象类,用来存储key/value,和map实现的功能类似,不过现在这个抽象类已经过时了,被map接口所取代。
第一:
继承的类有所不同
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable
第二:HashTable是线程安全的
看一下get方法的源码就知道了
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;
}
但是正是由于HashTable是线程安全的,因为锁的存在,这也是的HashTable 的性能不如HashMap。
第三:
Key、Value均不能为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;
}
如果为null,就会抛出一个NullPointerException,这一点和HashMap区别还是蛮大的。
如有错误,欢迎指正