问题描述
我已经知道拥有键值对时使用HashMap,不需要重复数据时使用HashSet.但是我总是对Hashtable发挥作用的地方感到困惑.它是一个完全不同的数据结构吗?还是HashMap和HashSet都使用哈希函数将数据存储在Hashtable中??详尽的解释将非常有帮助.
I already know that we use HashMap when we have Key-Value pair and we use HashSet when we do not need repetitive data. But I always get confused where Hashtable comes into play. Is it a totally different data structure? Or both HashMap and HashSet use hash function to store data in Hashtable? Thorough explanation will be really helpful .
推荐答案
更具体地讲, HashSet
在内部使用 HashMap
,查看 HashSet的实现.java
More specific, HashSet
uses internally a HashMap
, look at the implementation of HashSet.java
private transient HashMap<E,Object> map;
如先前的回答以及HashMap的JavaDoc中所述,HashMap实现基于哈希表数据结构:
As stated in a previous answer and in the JavaDoc of the HashMap, the HashMap implementation is based on a hash table data-structure:
java.util包中还有一个 Hashtable
(可识别小写的 t ).JavaDoc中也说明了主要区别:
There is also a Hashtable
(recognize the lower case t) available in the java.util package. The main difference is stated also in the JavaDoc:
也就是说,JavaDoc声明不应使用 Hashtable
.如果需要线程安全的实现,请使用 ConcurrentHashMap
,否则请使用 HashMap
.如果需要并发集,则应查看为什么没有针对的ConcurrentHashSetConcurrentHashMap .如果您正在寻找一个好的集合实现,请使用 HashSet
(在内部,除了 HashMap
之外,什么都没有).
That said, the JavaDoc states that Hashtable
should never be used. If you need a thread-safe implementation use ConcurrentHashMap
, otherwise use a HashMap
. If you need a concurrent set you should have a look at Why there is no ConcurrentHashSet against ConcurrentHashMap. If you are looking for a good set implementation just use HashSet
(which is internally nothing else than a HashMap
).
这篇关于HashSet和HashMap都使用Hashtable吗?还是Hashtable是完全不同的数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!