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

Does HashSet and HashMap both use Hashtable ? Or Hashtable is totally different data structure?

我已经知道,当我们有Key-Value对时我们使用HashMap,当我们不需要重复数据时我们使用HashSet。但是我总是对 Hashtable 发挥作用的地方感到困惑。它是一个完全不同的数据结构吗? 或者HashMap和HashSet都使用哈希函数在Hashtable中存储数据?详尽的解释将非常有帮助。

HashMapHashSet 都使用散列 table(注意小写!),这是编写某种数据结构的一般方式的名称。你可以写你自己的散列 table;我写了我自己的散列 tables; hash tables 只是一种通用的数据结构设计,就像你可以拥有不使用 LinkedList 实现的链表一样。 (注意 HashSet 实际上是使用 HashMap 实现的,但这对你的问题来说并不是特别重要。)

Hashtable 是像 HashMap 一样工作的类型的 Java API 不再推荐使用,因为 HashMap 完成了它的工作更好,基本上。你不应该使用它。

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

的实现
private transient HashMap<E,Object> map;

如前一个答案和 HashMap 的 JavaDoc 中所述,HashMap 实现基于散列 table 数据结构:

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)。