前幾天被一家公司電面的時候被問到HashMap和HashTable的區別,當時就懵逼了,hashTable是個啥?歷來沒用過啊,因而電面完以後立刻google了一把,這回漲姿式了;java
HashMap和HashTable同屬於Java.util包下的集合類,Hashtable是個過期的集合類,存在於Java API中好久了。在Java 4中被重寫了,實現了Map接口,因此自此之後也成了Java集合框架中的一部分。安全
HashMap和Hashtable都實現了Map接口,但決定用哪個以前先要弄清楚它們之間的分別。主要的區別有:線程安全性,同步(synchronization),以及速度。多線程
對比項 | HashMap | HashTable |
是否線程安全 | 否 | 是 |
是否synchronized | 否 | 是 |
是否支持多線程共享 | 在有正確的同步機制的前提下能夠支持多線程共享 | 支持 |
單線程效率 | 高 | 底 |
只隨時間推移元素次序是否不變 | 不必定 | 是 |
是否支持null的key和value | 支持 | 不支持 |
另外一個區別是HashMap的迭代器(Iterator)是fail-fast迭代器,而Hashtable的enumerator迭代器不是fail-fast的。因此當有其它線程改變了HashMap的結構(增長或者移除元素),將會拋出ConcurrentModificationException,但迭代器自己的remove()方法移除元素則不會拋出ConcurrentModificationException異常。但這並非一個必定發生的行爲,要看JVM。這條一樣也是Enumeration和Iterator的區別。app
Java 5提供了ConcurrentHashMap,它是HashTable的替代,比HashTable的擴展性更好。同時HashMap也能夠經過如下方式進行同步操做,返回的Map就是一個框架
HashMap<String, String> hashMap = new HashMap<String, String>(); Map map = Collections.synchronizedMap(hashMap); *****synchronizedMap的方法API描述***** Returns a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map.It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views: Map m = Collections.synchronizedMap(new HashMap()); ... Set s = m.keySet(); // Needn't be in synchronized block ... synchronized(m) { // Synchronizing on m, not s! Iterator i = s.iterator(); // Must be in synchronized block while (i.hasNext()) foo(i.next()); } Failure to follow this advice may result in non-deterministic behavior.The returned map will be serializable if the specified map is serializable. Parameters: m the map to be "wrapped" in a synchronized map. Returns: a synchronized view of the specified map.
通常的話僅在須要 徹底的線程安全的時候使用Hashtable,而若是你使用Java 5或以上的話,請使用ConcurrentHashMap代替HashTable;this