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

本文探讨了Java中HashMap与Hashtable的主要区别,包括同步性、对null的支持及迭代顺序等,并介绍了ConcurrentHashMap作为高并发场景下的更好选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值