What are the differences between a HashMap and a Hashtable in Java?

后端 未结 30 2344
青春惊慌失措
青春惊慌失措 2020-11-21 13:30

What are the differences between a HashMap and a Hashtable in Java?

Which is more efficient for non-threaded applications?

相关标签:
30条回答
  • 2020-11-21 13:42

    This question is often asked in interview to check whether candidate understands correct usage of collection classes and is aware of alternative solutions available.

    1. The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
    2. HashMap does not guarantee that the order of the map will remain constant over time.
    3. HashMap is non synchronized whereas Hashtable is synchronized.
    4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort.

    Note on Some Important Terms:

    1. Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a Hashtable will have to acquire a lock on the object while others will wait for lock to be released.
    2. Fail-safe is relevant within the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke set method since it doesn't modify the collection "structurally". However, if prior to calling set, the collection has been modified structurally, IllegalArgumentException will be thrown.
    3. Structurally modification means deleting or inserting element which could effectively change the structure of map.

    HashMap can be synchronized by

    Map m = Collections.synchronizeMap(hashMap);

    Map provides Collection views instead of direct support for iteration via Enumeration objects. Collection views greatly enhance the expressiveness of the interface, as discussed later in this section. Map allows you to iterate over keys, values, or key-value pairs; Hashtable does not provide the third option. Map provides a safe way to remove entries in the midst of iteration; Hashtable did not. Finally, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called contains, which returns true if the Hashtable contains a given value. Given its name, you'd expect this method to return true if the Hashtable contained a given key, because the key is the primary access mechanism for a Hashtable. The Map interface eliminates this source of confusion by renaming the method containsValue. Also, this improves the interface's consistency — containsValue parallels containsKey.

    The Map Interface

    0 讨论(0)
  • 2020-11-21 13:42

    Apart from the differences already mentioned, it should be noted that since Java 8, HashMap dynamically replaces the Nodes (linked list) used in each bucket with TreeNodes (red-black tree), so that even if high hash collisions exist, the worst case when searching is

    O(log(n)) for HashMap Vs O(n) in Hashtable.

    *The aforementioned improvement has not been applied to Hashtable yet, but only to HashMap, LinkedHashMap, and ConcurrentHashMap.

    FYI, currently,

    • TREEIFY_THRESHOLD = 8 : if a bucket contains more than 8 nodes, the linked list is transformed into a balanced tree.
    • UNTREEIFY_THRESHOLD = 6 : when a bucket becomes too small (due to removal or resizing) the tree is converted back to linked list.
    0 讨论(0)
  • 2020-11-21 13:42

    HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys. ut there are many differences between HashMap and Hashtable classes that are given below.

    0 讨论(0)
  • 2020-11-21 13:43

    HashMap is emulated and therefore usable in GWT client code whereas Hashtable is not.

    0 讨论(0)
  • 2020-11-21 13:45

    There is many good answer already posted. I'm adding few new points and summarizing it.

    HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys. But there are many differences between HashMap and Hashtable classes that are given below.

    HashMap

    1. HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code.
    2. HashMap allows one null key and multiple null values.
    3. HashMap is a new class introduced in JDK 1.2.
    4. HashMap is fast.
    5. We can make the HashMap as synchronized by calling this code
      Map m = Collections.synchronizedMap(HashMap);
    6. HashMap is traversed by Iterator.
    7. Iterator in HashMap is fail-fast.
    8. HashMap inherits AbstractMap class.

    Hashtable

    1. Hashtable is synchronized. It is thread-safe and can be shared with many threads.
    2. Hashtable doesn't allow any null key or value.
    3. Hashtable is a legacy class.
    4. Hashtable is slow.
    5. Hashtable is internally synchronized and can't be unsynchronized.
    6. Hashtable is traversed by Enumerator and Iterator.
    7. Enumerator in Hashtable is not fail-fast.
    8. Hashtable inherits Dictionary class.

    Further reading What is difference between HashMap and Hashtable in Java?

    0 讨论(0)
  • 2020-11-21 13:45

    Another key difference between hashtable and hashmap is that Iterator in the HashMap is fail-fast while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort."

    My source: http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html

    0 讨论(0)
提交回复
热议问题