java的HashMap和HashTable有啥区别?怎么使用的?新手哈!
首先Hashtable和HashMap都实现了java.util.Map
接口,但Hashtable扩展自java.util.Dictionary
而HashMap扩展自java.util.AbstractMap
,内部的就不提了,从使用上看下有什么区别:
Hashtable的
key
和value
必须是非null
的,而HashMap的key
和value
都允许为null
;Hashtable是线程安全的,而HashMap是非线程安全的;
Hashtable多了一些公开方法,如
contains
等同于HashMap的containsValue
;多了elements
和keys
,继承自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
替代。另外相似的官方建议替代的类有:
java.util.Vector
建议使用java.util.ArrayList
替代;java.util.Stack
建议使用java.util.ArrayDeque
替代;
以上来自 Java7
有3类:hashtable, hashmap, concurrenthashmap
hashtable是线程安全多用于多线程开发
hashmap是线程非安全,所以用在多线程中有一定问题
concurrenthashmap也是同步的,但是优于hashtable,因为hashtable是整张表加锁,而它是分段加锁机制
HashTable是同步的,可以在多线程下使用,HashMap不是多线程安全的。