BEN asked in 電腦與網際網路程式設計 · 1 decade ago

hashmap和hashtable的差異

hashmap和hashtable有什麼差異

這是我去面試時遇到的題目

請會的人解釋一下

1 Answer

Rating
  • 1 decade ago
    Favorite Answer

    HashTable和HashMap的不同主要有四種1. 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) 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"2. HashMap 的Key跟Value都可以是null,HashTable則不行 也就是在HashMap裡可以這麼寫: HashMap m = new HashMap(); m.put("1",null); m.put(null, new Integer(2));3. 最大的不同是 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(...));4. HashMap拿掉了HashTable的contains(Object value) 因為這個method容易造成混淆,到底是contains key還是value? 這個method改用containsValue(Object value)取代掉了。

Still have questions? Get your answers by asking now.