

Java HashMap 与 Hashtable 的区别
source link: https://wangzhiyao.github.io/articles/java-hashmap-hashtab/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java HashMap 与 Hashtable 的区别
1.HashMap
HashMap 不是线程安全的,HashMap 是 Map 接口的实现类,是将键映射到值的对象,其中键和值都是对象,并且不能包含重复键,但可以包含重复值。HashMap 允许 null key 和 null value, HashMap 是 HashTable 的轻量级实现 ,由于非线程安全,效率可能会比 Hashtable 高。
需要线程安全的 HashMap 可以使用 ConcurrentHashMap,其中 put 方法使用了 synchronized 加上线程锁。
2.Hashtable
Hashtable 是线程安全的,是 Map 接口的实现类,不允许 null key 和 null value,主要方法都使用了 synchronized 线程锁。
3.主要区别
- HashMap允许将 null 作为一个 entry 的 key 或者 value,而 Hashtable 不允许。
- HashMap 把 Hashtable 的 contains 方法去掉了,改成 containsValue 和 containsKey。因为 contains 方法容易让人引起误解。
- Hashtable 继承自 Dictionary,而 HashMap 继承自 AbstractMap,而 AbstractMap 是 Java1.2 引进的 Map 接口的一个实现类。
- Hashtable 的方法是线程安全的,而 HashMap 不是,在多个线程访问 Hashtable 时,不需要自己为它的方法实现同步,而 HashMap 就必须手动提供外同步。
- HashTable中的 initialCapacity 初始大小是11,增加的方式是 (oldCapacity << 1) + 1 即为 oldCapacity * 2 + 1。HashMap 中 initialCapacity 数组的默认大小是 16,增加的方式是 oldCapacity << 1。 loadFactor 同为 0.75。
Recommend
-
64
首先请先阅读这两个的源码。一、hashMap、hashTable都是Map接口的实现类,但是hashMap类继承自抽象类abstractMap类,hashTable继承自Dictionary类,该类在jdk中这样描述:可见该类已经过时。二、hashTable里面的方法都是...
-
76
-
51
-
38
An HashTable is a simpl...
-
44
Hashtable、HashMap、TreeMap都是比较常见的一些Map实现,它们都是 key-value 键值对的形式存储和操作数据的容器类,同时他们的元素中不能有重复的key,一个key也只能映射一个value值。 下面我从不同的维度来分别...
-
14
【Java】HashMap 和 HashTable 的区别到底是什么? 第一、继承不同第一个不同主要是历史原因。Hashtable是基于陈旧的Dictionary类的,HashMap是Java 1.2引进的Map接口的一个实现。 ...
-
6
基于J11,该类已经淘汰,如果使用线程安全的则用 ConcurrentHashMap ,用线程不安全的则使用 HashMap 。仅与HashMap进行比较 结构以及依赖关系 HashTable 的结构如下图
-
3
本文已收录到 AndroidFamily,技术和职场问题,请关注公众号 [彭旭锐] 提问。 大家好,我是小彭。
-
8
Social Follow us on social media for more news, content and background stories from our authors, editors and events. Share your personal experience with us.
-
9
HashMap vs Hashtable – a comparison of two data structures who share similar functionality but have majorly distinctive features and implementation. Think of HashMap and Hashtable as companions that shine in their own specific use cases instead...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK