HashMap和HashTable的区别

HashMap继承了AbstractMap抽象类,同时实现了Map接口,从如下源代码中我们可以看出:
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

HashTable继承了Dictionary抽象类,同时实现了Map接口,代码如下:
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable

HashTable的方法是同步的,而HashMap的方法不是。也就是,虽然你可以不用采取任何特殊的行为就可以在一个多线程的应用程序中用一个Hashtable,但你必须同样的为一个HashMap提供外同步。一个方便的方法就是利用Collections类的静态的synchronizedMap()方法,它创建一个线程安全的Map对象,并把它作为一个封装的对象来返回。这个对象的方法可以让你同步访问潜在的HashMap。这么做的结果就是当你不需要同步时,你不能切断Hashtable中的同步(比如在一个单线程的应用程序中),而且同步增加了很多处理费用。
同时,HashMap可以让你将空值作为一个表的条目的key或value。HashMap中只有一条记录可以是一个空的key,但任意数量的条目可以是空的value。这就是说,如果在表中没有发现搜索键,或者如果发现了搜索键,但它是一个空的值,那么get()将返回null。如果有必要,用containKey()方法来区别这两种情况。一句话总结就是HashMap允许空键值,而Hash不行。

HashMap和HashTable的代码示例比较:

package org.shen.own;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;

public class Hash {
static HashMap<String, String> hm = new HashMap<String, String>();
static Hashtable<String, String> ht = new Hashtable<String, String>();
public static void main(String[] args) {
hm.put("1", "a");
hm.put("2", "b");
hm.put("3", "c");
hm.put("4", "d");
hm.put("5", "e");
hm.put("6", "f");

ht.put("a1", "a");
ht.put("b2", "b");
ht.put("c3", "c");
ht.put("d4", "d");
ht.put("e5", "e");
ht.put("f6", "f");

System.out.println(hm.containsKey("a")); //F
System.out.println(hm.containsKey("g")); //F
System.out.println(hm.containsValue("a")); //t
System.out.println(hm.entrySet()); //[3=c, 2=b, 1=a, 6=f, 5=e, 4=d] 里面的元素没有进行排序
System.out.println();

System.out.println(ht.contains("a")); // true
System.out.println(ht.containsValue("a")); //value为a的值 true
Enumeration<String> e= ht.elements();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}// a b c d e f g
System.out.println(ht.entrySet()); //[a1=a, b2=b, c3=c, d4=d, e5=e, f6=f] 里面的元素排序过
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值