[轉]HashTable vs HashMap

HashTable和HashMap的不同主要有四種:

一、HashTable 是繼承java.util.Dictionary
HashMap 是繼承java.util.AbstractMap

Dictionary 是舊的class,
【DOC】NOTE: This class is obsolete.
New implementations should implement the Map interface, rather than
extending this class.

java.util.AbstractMap 已經implements Map Interface,因此繼承它的class

只需要實作它的method就可以實作出需要的Map (例如get,put,entrySet method)
可參:http://java.sun.com/j2se/1.4.2/docs/api/java/util/AbstractMap.html

java.util.Dictionary 並沒有去Implements Map Interface,HashTable是另外去
implements Map interface,也因此HashTable能被算在Java Util Framework中。

【DOC】" As of the Java 2 platform v1.2, this class has been retrofitted to implement Map, so that it becomes a part of Java's collection framework"
另外,Dictionary只提供最基本的abstract method

【DOC】"The Dictionary class is the abstract parent of any class, such as Hashtable, which maps keys to values"

二、HashMap 的Key跟Value都可以是null,HashTable則不行

也就是在HashMap裡可以這麼寫:
HashMap m = new HashMap();
m.put("1",null);
m.put(null, new Integer(2));

三、最大的不同是 HashTable的method是 Synchronized,而HashMap則沒有

【DOC】"Unlike the new collection implementations, Hashtable is synchronized."

因此有兩個情形要考慮:

(1)沒有Multithread的情形下,使用HashMap即可,因為HashTable有作Synchronization,相對地它的Performance是劣於HashMap的

(2)有Multithread情形時,如果要使用HashMap,要作外部的Synchronization
【DOC】"If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally."

方法有很多種,API DOC裡提到可以對包含這個Map的Object作Synchronized
Map m = Collections.synchronizedMap(new HashMap(...));

四、HashMap拿掉了HashTable的contains(Object value)因為這個method容易造成混淆倒底是contains key還是value?? 這個method改用containsValue(Object value)取代掉了。

ref:http://psalter.spaces.live.com/blog/cns!F7AA90C7BB6EC803!124.entry
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值