Hashtable 与HashMap 的区别

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遍历的话则是从大到小的**

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值