HashSet和HashMap都使用Hashtable吗?还是Hashtable是完全不同的数据结构? [英] Does HashSet and HashMap both use Hashtable ? Or Hashtable is totally different data structure?

查看:80
本文介绍了HashSet和HashMap都使用Hashtable吗?还是Hashtable是完全不同的数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道拥有键值对时使用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:

基于哈希表的Map接口的实现.此实现提供所有可选的映射操作,并允许空值和空键.(HashMap类与Hashtable大致等效,不同之处在于它是不同步的,并且允许为null.)该类不保证映射的顺序;它不保证映射的顺序.特别是,它不能保证顺序会随着时间的推移保持恒定.

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中也说明了主要区别:

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:

与新的集合实现不同,Hashtable是同步的.如果不需要线程安全的实现,建议使用HashMap代替Hashtable.如果需要线程安全的高度并发实现,则建议使用ConcurrentHashMap代替Hashtable.

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 .如果需要并发集,则应查看为什么没有针对的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是完全不同的数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆