Differences between HashMap and Hashtable?
如何来选用:
如果同步不是主要问题,推荐使用HashMap,如果同步问题是个问题,应该参照ConcurrentHashMap这个类。
There are several differences between HashMap and Hashtable in Java:
-
Hashtable is synchronized, where as HashMap is not. This makes
HashMap
better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. -
Hashtable
does not allow null keys or values.HashMap
allows one null key and any number ofnull
values. -
One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the
HashMap
for aLinkedHashMap
. This wouldn't be as easy if you were usingHashtable
.
Since synchronization is not an issue for you, I'd recommend HashMap
. If synchronization becomes an issue, you may also look at ConcurrentHashMap.
类ConcurrentHashMap:
ConcurrentHashMap和
java.util.HashTable
类非常相似, ConcurrentHashMap
比 HashTable
有更好的并发性。 ConcurrentHashMap在读取数据的时候
不会给 Map加锁
。除此之外, ConcurrentHashMap
在写入数据的时候,不锁住整个。 它只对Map中将要写入的数据的那一部分内存加锁 ,
另一个不同点是如果ConcurrentHashMap在迭代的过程中改变了数据,ConcurrentHashMap
不抛出ConcurrentModificationException
异常。迭代器 Iterator
不是设计来为多线程使用的。
例子:
ConcurrentMap concurrentMap = new ConcurrentHashMap(); concurrentMap.put("key", "value"); Object value = concurrentMap.get("key");