gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:21:23 25 4
gpt4 key购买 nike

我已经知道,当我们有键值对时,我们使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com