HashMap 与 HashTable 的区别

HashMap 与 HashTable 的区别

HashMap 和 HashTable 都是 Java 中基于哈希表实现的 Map 接口的实现类,但它们有以下几个关键区别:

1. 线程安全性

HashMapHashTable
线程安全非线程安全线程安全 (方法使用 synchronized 修饰)
同步需要外部同步内部同步
// HashMap 需要外部同步
Map<String, String> hashMap = new HashMap<>();
Map<String, String> syncMap = Collections.synchronizedMap(hashMap);

// HashTable 内部同步
Map<String, String> hashTable = new Hashtable<>();

2. null 键/值处理

HashMapHashTable
null键允许1个不允许
null值允许多个不允许
HashMap<String, String> hm = new HashMap<>();
hm.put(null, "value");  // 允许
hm.put("key", null);    // 允许

Hashtable<String, String> ht = new Hashtable<>();
ht.put(null, "value");  // 抛出 NullPointerException
ht.put("key", null);    // 抛出 NullPointerException

3. 性能比较

HashMapHashTable
性能更高较低
原因无同步开销同步方法带来性能损耗

4. 迭代器

HashMapHashTable
迭代器fail-fastfail-fast
(快速失败)(快速失败)
枚举不支持支持
Hashtable<String, String> ht = new Hashtable<>();
Enumeration<String> keys = ht.keys();  // HashTable 特有

5. 继承体系

java.util.Dictionary (已废弃)
       ↑
   Hashtable

java.util.AbstractMap
       ↑
     HashMap

6. 初始容量与扩容

HashMapHashTable
默认初始容量1611
扩容方式2n2n+1

7. 使用建议

  1. 使用 HashMap 的情况

    • 单线程环境

    • 需要更高的性能

    • 需要存储 null 键/值

  2. 使用 HashTable 的情况

    • 遗留系统维护

    • 需要线程安全且不介意性能损耗

    • 不需要存储 null 键/值

8. 替代方案

对于线程安全的 Map 实现,更推荐使用:

  • ConcurrentHashMap (JDK 1.5+)

  • Collections.synchronizedMap()

ConcurrentHashMap 示例:

Map<String, String> concurrentMap = new ConcurrentHashMap<>();
// 比 HashTable 更高的并发性能

总结对比表

特性HashMapHashTable
线程安全不安全安全(synchronized)
null键值允许不允许
性能更高较低
迭代器IteratorIterator + Enumeration
继承类AbstractMapDictionary
初始容量1611
扩容方式2n2n+1
推荐使用场景单线程/高并发替代遗留系统
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暮乘白帝过重山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值