Java 面试常见问题之——Hashtable 和 Hashmap 的区别

Java 面试常见问题之——Hashtable 和 Hashmap 的区别

在 Java 中,Hashtable 和 HashMap 都是常用的用于存储键值对的数据结构,但它们在许多方面存在着显著的区别。

一、线程安全性

Hashtable 是线程安全的,这意味着多个线程可以同时访问和修改 Hashtable 中的数据,而不需要额外的同步措施。它的方法都被 synchronized 关键字修饰,以确保在多线程环境下数据的一致性和正确性。
HashMap 则是非线程安全的。在多线程环境下,如果多个线程同时访问和修改 HashMap,可能会导致数据不一致或者抛出 ConcurrentModificationException 异常。如果需要在多线程环境中使用 HashMap,可以通过使用 Collections.synchronizedMap() 方法将其包装成线程安全的,或者使用 ConcurrentHashMap。

例如:

Hashtable<String, String> hashtable = new Hashtable<>();

Thread thread1 = new Thread(() -> {
    hashtable.put("key1", "value1");
});

Thread thread2 = new Thread(() -> {
    hashtable.put("key2", "value2");
});

thread1.start();
thread2.start();

二、空值处理

Hashtable 不允许键或值为 null 。以下操作会抛出异常:

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

HashMap 允许键为 null ,但只能有一个键为 null 的键值对,值也可以为 null 。

HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(null, "value"); 
hashMap.put("key", null); 

三、性能

由于 Hashtable 的线程安全特性,在单线程环境下,HashMap 性能通常更好。
假设进行大量的插入操作:

long start = System.currentTimeMillis();
Hashtable<String, String> hashtable = new Hashtable<>();
for (int i = 0; i < 100000; i++) {
    hashtable.put("key" + i, "value" + i);
}
long end = System.currentTimeMillis();
System.out.println("Hashtable 插入耗时: " + (end - start) + " 毫秒");

start = System.currentTimeMillis();
HashMap<String, String> hashMap = new HashMap<>();
for (int i = 0; i < 100000; i++) {
    hashMap.put("key" + i, "value" + i);
}
end = System.currentTimeMillis();
System.out.println("HashMap 插入耗时: " + (end - start) + " 毫秒");

通常 HashMap 的耗时会更少。

总结

  • 1、HashTable 线程安全,HashMap 非线程安全
  • 2、Hashtable 不允许 null 值(key 和 value 都不可以),HashMap允许 null 值(key和value都可以)。
  • 3、两者的遍历方式大同小异,Hashtable仅仅比HashMap多一个elements方法。
  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值