Hashtable与HashMap都实现了Map接口,主要区别在于:
线程安全性,同步(synchronization) 和 速度
①Hashtable不允许有null(key和value都不行),HashMap允许有null(key和value都可以)
②HashMap中只允许有一个null的key,但是可以有多个null的value。即当调用get()是否等于null,不能判断是否存在该键,因为null既可以表示不存在该键,也可以表示该键为null。
③HashTable用 Enumeration,HashMap用iterat进行遍历
④HashTable是线程安全的,HashMap是线程不安全的。因为HashTable的实现运用了synchronized锁,而HashMap则是非synchronized的。多个线程可以共享HashTbale,但是如果多个线程没有正确的同步性的话,是不能共享HashMap
public class test {
public static void main(String[] args){
HashMap<Integer,String> hm=new HashMap<Integer,String>();
Hashtable<Integer,String> ht=new Hashtable<Integer,String>();
//验证HashMap可以存在null,而Hashtable不允许存在
hm.put(0, "M_first");
hm.put(1, "M_second");
hm.put(2, "M_third");
hm.put(null, null);
ht.put(0, "T_first");
ht.put(1, "T_second");
ht.put(2, "T_third");
//ht.put(null, null);
//去掉上一行的注释符则编译错误
//Hashtable---enumeration与HashMap---iterator的区别
//enumeration是JDK1.0时候推出的,是最好的迭代输出接口,JAK1.5之后为此类进行了扩充
//增加了泛型的操作应用;enumeration接口常用的方法为hasMoreElements()(判断是否有下一
//个值,nextElements()(取出当前元素),这些方法与iterator相似,但是iterator有删除操作
//因为Hashtable没有实现iterable接口
//public class Hashtable<K,V>extends Dictionary<K,V>implements Map<K,V>, Cloneable, Serializable
Iterator<Integer> sm_k=hm.keySet().iterator();//使用迭代器获取key
Iterator<Entry<Integer, String>> sm_kv=hm.entrySet().iterator();//使用迭代器获取key_value对
// Collection<String> sm_v=hm.values();//将value映射到collection视图
// Iterator sv=sm_s.iterator();//利用迭代器获取
// while(sv.hasNext()) System.out.print(sv.next()+" "); //HashMap的value
Enumeration<String> st_v=ht.elements();
Enumeration<Integer> st_k=ht.keys();//使用枚举获得KEY
Set<Entry<Integer,String>> st_kv=ht.entrySet();
System.out.println("HashMap");
while(sm_k.hasNext()){
System.out.println(" KEY: "+sm_k.next()+" VALUE: "+sm_kv.next());
}
// while(sm_kv.hasNext())System.out.print(sm_kv.next()+" ");
System.out.println();
System.out.println("Hashtable");
while(st_k.hasMoreElements()){
System.out.println("KEY: "+st_k.nextElement()+" VALUE: "+st_v.nextElement()+" ");
}
// while(st_v.hasMoreElements())System.out.print(st_v.nextElement());}}
**而且由上面结果也可以得出iterator迭代的话是从小往大遍历的
而由enumeration遍历的话则是从大到小的**