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

僤鯓⒐⒋嵵緔 提交于 2021-02-08 09:51:30

问题


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 .


回答1:


More specific, HashSet uses internally a HashMap, look at the implementation of HashSet.java

private transient HashMap<E,Object> map;

As stated in a previous answer and in the JavaDoc of the HashMap, the HashMap implementation is based on a hash table data-structure:

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.

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:

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.

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




回答2:


Both HashMap and HashSet use a hash table (note the lower case!) which is a name for a general way of writing a certain kind of data structure. You can write your own hash table; I've written my own hash tables; hash tables are just a general data structure design, just like you can have linked lists that aren't implemented using LinkedList. (Note HashSet is actually implemented using HashMap, but this isn't particularly important for your question.)

Hashtable is the Java API for a type that worked like HashMap that is no longer recommended for use, since HashMap does its job better, basically. You should never use it.



来源:https://stackoverflow.com/questions/36122981/does-hashset-and-hashmap-both-use-hashtable-or-hashtable-is-totally-different

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!