首页 > HashMap和Hashtable有啥区别?

HashMap和Hashtable有啥区别?

java的HashMap和HashTable有啥区别?怎么使用的?新手哈!


首先HashtableHashMap都实现了java.util.Map接口,但Hashtable扩展自java.util.DictionaryHashMap扩展自java.util.AbstractMap,内部的就不提了,从使用上看下有什么区别:

  1. Hashtablekeyvalue必须是非null的,而HashMapkeyvalue都允许为null

  2. Hashtable是线程安全的,而HashMap是非线程安全的;

  3. Hashtable多了一些公开方法,如contains等同于HashMapcontainsValue;多了elementskeys,继承自java.util.Dictionary返回的都是Enumeration类型

另外,其实java是不推荐使用Hashtable的,见doc:

If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use java.util.concurrent.ConcurrentHashMap in place of Hashtable.

非线程安全情况下,推荐使用HashMap替代Hashtable;高并发线程安全情况下,推荐使用ConcurrentHashMap替代Hashtable

Hashtable继承的Dictionary也被官方标定为过时的(obsolete),推荐以Map替代。另外相似的官方建议替代的类有:


以上来自 Java7


有3类:hashtable, hashmap, concurrenthashmap
hashtable是线程安全多用于多线程开发
hashmap是线程非安全,所以用在多线程中有一定问题
concurrenthashmap也是同步的,但是优于hashtable,因为hashtable是整张表加锁,而它是分段加锁机制


HashTable是同步的,可以在多线程下使用,HashMap不是多线程安全的。

【热门文章】
【热门文章】