java - HashSet 和 HashMap 都使用 Hashtable 吗?或者Hashtable是完全不同的数据结构?

标签 java hashmap hashtable hashset

我已经知道,当我们有键值对时,我们使用 HashMap,当我们不需要重复数据时,我们使用 HashSet。但我总是很困惑 Hashtable 在哪里发挥作用。这是完全不同的数据结构吗? 或者HashMap和HashSet都使用哈希函数在Hashtable中存储数据?彻底的解释将会非常有帮助。

最佳答案

更具体一点,HashSet内部使用了一个HashMap,看HashSet.java的实现

private transient HashMap<E,Object> map;

正如之前的回答和 HashMap 的 JavaDoc 中所述,HashMap 实现基于哈希表数据结构:

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

java.util 包中还有一个 Hashtable(识别小写的 t)。 JavaDoc 中也说明了主要区别:

Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended ConcurrentHashMap in place of Hashtable.

也就是说,JavaDoc 规定永远不应该使用Hashtable。如果您需要线程安全的实现,请使用ConcurrentHashMap,否则使用HashMap。如果您需要并发集,您应该看看 Why there is no ConcurrentHashSet against ConcurrentHashMap 。如果您正在寻找一个好的集合实现,只需使用 HashSet (它的内部只不过是一个 HashMap)。

关于java - HashSet 和 HashMap 都使用 Hashtable 吗?或者Hashtable是完全不同的数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36122981/

相关文章:

java - 我的哈希表应该使用什么大小的存储桶?

c# - 具有单个键的多个值的哈希表

android - Retrofit - 如何将 Response 转换为 HashMap?

c++ - 在 C++ 中创建哈希表以进行字符串操作

java - 为什么我的 Spring 服务返回客户端请求的任何内容类型?

java - 如何获取A时间和B时间之间的差距?

java - 由于性能问题双重字符串替代

java - android listview doinbackground无法显示任何内容

Java - 如何使用 HashMap 来映射简单的数学运算符

java - 尝试向我的 Hashmap 添加一个实例方法,该方法采用两个代表键和值的参数