Hashtable
对于hashtable我不是太熟,只知道它是一个遗留类,名字取得不符合规则.
本文只是简单说一下Hashtable和HashMap的一些区别,不做深入研究.
Hashtable和HashMap 的区别
- 基类不同:HashTable基于Dictionary类,而HashMap是基于AbstractMap。Dictionary是什么?它是任何可将键映射到相应值的类的抽象父类,而AbstractMap是基于Map接口的骨干实现,它以最大限度地减少实现此接口所需的工作。
- 线程安全:HashMap时单线程安全的,Hashtable是多线程安全的。
HashMap源码
Hashtable源码
- 遍历不同:HashMap仅支持Iterator的遍历方式,Hashtable支持Iterator和Enumeration两种遍历方式。
- null不同:HashMap可以允许存在一个为null的key和任意个为null的value,但是HashTable中的key和value都不允许为null。
HashMap.put()的例子
public class HashMapDemo1 {
public static void main(String[] args) {
HashMap<String,String> hm=new HashMap<>();
//key为null
hm.put(null, "马");
hm.put(null, "荷");
//value为null
hm.put("王", null);
hm.put("陈", null);
//一般插入
hm.put("松", "榕");
hm.put("屁", "鹿");
Set<Entry<String, String>> entrySet = hm.entrySet();
for (Entry<String, String> entry : entrySet) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
结果:
HashMap的key和value值可以为null的源码(之前写的文章)
Hashtable.put()的例子:
public class HashTableDemo {
public static void main(String[] args) {
Hashtable<String, String> ht = new Hashtable<>();
ht.put(null, "马");
//ht.put("屁", null);
}
}
结果:
public class HashTableDemo {
public static void main(String[] args) {
Hashtable<String, String> ht = new Hashtable<>();
//ht.put(null, "马");
ht.put("屁", null);
}
}
结果:
Hashtable的put()源码
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 = hash(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;
hash = hash(key);
index = (hash & 0x7FFFFFFF) % tab.length;
}
value不能为空:
value不为null,key为null情况
结论:在Hashtable中,无论是key还是null,只要一个为null,都会报空指针异常
网上大神的见解Hashtable是支持并发的,这样会有一个问题,当你通过get(k)获取对应的value时,如果获取到的是null时,你无法判断,它是put(k,v)的时候value为null,还是这个key从来没有做过映射。HashMap是非并发的,可以通过contains(key)来做这个判断。而支持并发的Map在调用m.contains(key)和m.get(key),m可能已经不同了。:
参考文章
http://blog.csdn.net/jinhuoxingkong/article/details/52022999