HashMap与HashTable区别(Differences between HashMap and Hashtable)

来源:互联网 发布:外国身份证 知乎 编辑:程序博客网 时间:2024/05/10 22:57
在stackoverflow.com上看到这个标题

Differences between HashMap and Hashtable?

大意如下:

1,Hashtable是同步的,HashMap不是同步的。没有被同步的对象比同步的对象一般执行得更快,这使得HashMap更加适用于没有多线程的应用当中。
2,Hashtable不许与为null的键或者值。HashMap可以允许存在一个为null的键和任意多个null的值。
3,LinkedHashMap是一个HashMap的子类。对于一个LinkedHashMap,你可以按照预知迭代的顺序(按照默认插入的顺序),转换数据到HashMap。但是要转化为一个Hashtable可就难了。


如何来选用:

如果同步不是主要问题,推荐使用HashMap,如果同步问题是个问题,应该参照ConcurrentHashMap这个类。



There are several differences between HashMap and Hashtable in Java:

  1. 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.

  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.

  3. 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 a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.

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");




0 0