[轉]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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章