<p>What are the differences between a <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/HashMap.html" rel="noreferrer"><code>HashMap</code></a> and a <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Hashtable.html" rel="noreferrer"><code>Hashtable</code></a> in Java?</p>

<p>Which is more efficient for non-threaded applications?</p>

[{'answer_id': 40483, 'author': 'pkaeding', 'author_id': 4257, 'author_profile': 'https://Stackoverflow.com/users/4257', 'pm_score': 5, 'selected': False, 'text': '<p>Based on the info <a href="http://www.jguru.com/faq/view.jsp?EID=430247" rel="noreferrer">here</a>, I\'d recommend going with HashMap.  I think the biggest advantage is that Java will prevent you from modifying it while you are iterating over it, unless you do it through the iterator.</p>\n'}, {'answer_id': 40512, 'author': 'izb', 'author_id': 974, 'author_profile': 'https://Stackoverflow.com/users/974', 'pm_score': 6, 'selected': False, 'text': "<p><code>Hashtable</code> is synchronized, whereas <code>HashMap</code> isn't. That makes <code>Hashtable</code> slower than <code>Hashmap</code>.</p>\n<p>For single thread applications, use <code>HashMap</code> since they are otherwise the same in terms of functionality.</p>\n"}, {'answer_id': 40522, 'author': 'Miles D', 'author_id': 3898, 'author_profile': 'https://Stackoverflow.com/users/3898', 'pm_score': 6, 'selected': False, 'text': '<p><code>Hashtable</code> is similar to the <code>HashMap</code> and has a similar interface. It is recommended that you use <code>HashMap</code>, unless you require support for legacy applications or you need synchronisation, as the <code>Hashtables</code> methods are synchronised. So in your case as you are not multi-threading, <code>HashMaps</code> are your best bet.</p>\n'}, {'answer_id': 40548, 'author': 'matt b', 'author_id': 4249, 'author_profile': 'https://Stackoverflow.com/users/4249', 'pm_score': 6, 'selected': False, 'text': '<p>In addition to what izb said, <code>HashMap</code> allows null values, whereas the <code>Hashtable</code> does not.</p>\n\n<p>Also note that <code>Hashtable</code> extends the <code>Dictionary</code> class, which as the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/Dictionary.html" rel="noreferrer">Javadocs</a> state, is obsolete and has been replaced by the <code>Map</code> interface.</p>\n'}, {'answer_id': 40848, 'author': 'Tim Howland', 'author_id': 4276, 'author_profile': 'https://Stackoverflow.com/users/4276', 'pm_score': 4, 'selected': False, 'text': '<p>For threaded apps, you can often get away with ConcurrentHashMap- depends on your performance requirements.</p>\n'}, {'answer_id': 40878, 'author': 'Josh Brown', 'author_id': 2030, 'author_profile': 'https://Stackoverflow.com/users/2030', 'pm_score': 13, 'selected': True, 'text': '<p>There are several differences between <a href="http://java.sun.com/javase/7/docs/api/java/util/HashMap.html" rel="noreferrer"><code>HashMap</code></a> and <a href="http://java.sun.com/javase/7/docs/api/java/util/Hashtable.html" rel="noreferrer"><code>Hashtable</code></a> in Java:</p>\n\n<ol>\n<li><p><code>Hashtable</code> is <a href="https://stackoverflow.com/questions/1085709/what-does-synchronized-mean">synchronized</a>, whereas <code>HashMap</code> is not. This makes <code>HashMap</code> better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.</p></li>\n<li><p><code>Hashtable</code> does not allow <code>null</code> keys or values.  <code>HashMap</code> allows one <code>null</code> key and any number of <code>null</code> values.</p></li>\n<li><p>One of HashMap\'s subclasses is <a href="http://java.sun.com/javase/7/docs/api/java/util/LinkedHashMap.html" rel="noreferrer"><code>LinkedHashMap</code></a>, so in the event that you\'d want predictable iteration order (which is insertion order by default), you could easily swap out the <code>HashMap</code> for a <code>LinkedHashMap</code>.  This wouldn\'t be as easy if you were using <code>Hashtable</code>.</p></li>\n</ol>\n\n<p>Since synchronization is not an issue for you, I\'d recommend <code>HashMap</code>. If synchronization becomes an issue, you may also look at <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="noreferrer"><code>ConcurrentHashMap</code></a>.</p>\n'}, {'answer_id': 40894, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 7, 'selected': False, 'text': "<p><code>HashMap</code>: An implementation of the <code>Map</code> interface that uses hash codes to index an array.\n<code>Hashtable</code>: Hi, 1998 called. They want their collections API back.</p>\n\n<p>Seriously though, you're better off staying away from <code>Hashtable</code> altogether. For single-threaded apps, you don't need the extra overhead of synchronisation. For highly concurrent apps, the paranoid synchronisation might lead to starvation, deadlocks, or unnecessary garbage collection pauses. Like Tim Howland pointed out, you might use <code>ConcurrentHashMap</code> instead.</p>\n"}, {'answer_id': 41454, 'author': 'serg10', 'author_id': 1853, 'author_profile': 'https://Stackoverflow.com/users/1853', 'pm_score': 10, 'selected': False, 'text': '<p>Note, that a lot of the answers state that Hashtable is synchronized.  <strong>In practice this buys you very little.</strong>  The synchronization is on the accessor/mutator methods will stop two threads adding or removing from the map concurrently, but in the real world, you will often need additional synchronization.</p>\n<p>A very common idiom is to &quot;check then put&quot; — i.e. look for an entry in the <code>Map</code>, and add it if it does not already exist. This is not in any way an atomic operation whether you use <code>Hashtable</code> or <code>HashMap</code>.</p>\n<p>An equivalently synchronised <code>HashMap</code> can be obtained by:</p>\n<pre><code>Collections.synchronizedMap(myMap);\n</code></pre>\n<p>But to correctly implement this logic you need <strong>additional synchronisation</strong> of the form:</p>\n<pre><code>synchronized(myMap) {\n    if (!myMap.containsKey(&quot;tomato&quot;))\n        myMap.put(&quot;tomato&quot;, &quot;red&quot;);\n}\n</code></pre>\n<p>Even iterating over a <code>Hashtable</code>\'s entries (or a <code>HashMap</code> obtained by <code>Collections.synchronizedMap</code>) is not thread-safe unless you also guard the <code>Map</code> against being modified through additional synchronization.</p>\n<p>Implementations of the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentMap.html" rel="noreferrer"><code>ConcurrentMap</code></a> interface (for example <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentHashMap.html" rel="noreferrer"><code>ConcurrentHashMap</code></a>) solve some of this by including <strong>thread safe check-then-act semantics</strong> such as:</p>\n<pre><code>ConcurrentMap.putIfAbsent(key, value);\n</code></pre>\n'}, {'answer_id': 1041798, 'author': 'aberrant80', 'author_id': 124111, 'author_profile': 'https://Stackoverflow.com/users/124111', 'pm_score': 9, 'selected': False, 'text': "<p><code>Hashtable</code> is considered legacy code. There's nothing about <code>Hashtable</code> that can't be done using <code>HashMap</code> or derivations of <code>HashMap</code>, so for new code, I don't see any justification for going back to <code>Hashtable</code>.</p>\n"}, {'answer_id': 7344090, 'author': 'Neerja', 'author_id': 934204, 'author_profile': 'https://Stackoverflow.com/users/934204', 'pm_score': 5, 'selected': False, 'text': '<p>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."</p>\n\n<p>My source: <a href="http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html" rel="noreferrer">http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html</a></p>\n'}, {'answer_id': 7644118, 'author': 'sravan', 'author_id': 759012, 'author_profile': 'https://Stackoverflow.com/users/759012', 'pm_score': 8, 'selected': False, 'text': '<p>This question is often asked in interviews to check whether the candidate understands the correct usage of collection classes and is aware of alternative solutions available.</p>\n<ol>\n<li>The <code>HashMap</code> class is roughly equivalent to <code>Hashtable</code>, except that it is non synchronized and permits nulls. (<code>HashMap</code> allows null values as key and value whereas <code>Hashtable</code> doesn\'t allow <code>null</code>s).</li>\n<li><code>HashMap</code> does not guarantee that the order of the map will remain constant over time.</li>\n<li><code>HashMap</code> is non synchronized whereas <code>Hashtable</code> is synchronized.</li>\n<li>Iterator in the <code>HashMap</code> is fail-safe while the enumerator for the <code>Hashtable</code> is not and throw <code>ConcurrentModificationException</code> if any other Thread modifies the map structurally by adding or removing any element except <code>Iterator</code>\'s own <code>remove()</code>  method. But this is not a guaranteed behavior and will be done by JVM on best effort.</li>\n</ol>\n<p>Note on Some Important Terms:</p>\n<ol>\n<li>Synchronized means only one thread can modify a hash table at one point in time. Basically, it means that any thread before performing an update on a <code>Hashtable</code> will have to acquire a lock on the object while others will wait for the lock to be released.</li>\n<li>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 &quot;structurally&quot;, a concurrent modification exception will be thrown. It is possible for other threads though to invoke the <code>set</code> method since it doesn\'t modify the collection &quot;structurally&quot;. However, if prior to calling <code>set</code>, the collection has been modified structurally, <code>IllegalArgumentException</code> will be thrown.</li>\n<li>Structurally modification means deleting or inserting element which could effectively change the structure of the map.</li>\n</ol>\n<p><code>HashMap</code> can be synchronized by</p>\n<p><code>Map m = Collections.synchronizeMap(hashMap);</code></p>\n<p>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; <code>Hashtable</code> does not provide the third option. Map provides a safe way to remove entries in the midst of iteration; <code>Hashtable</code> did not. Finally, Map fixes a minor deficiency in the <code>Hashtable</code> interface. <code>Hashtable</code> has a method called contains, which returns true if the <code>Hashtable</code> contains a given value. Given its name, you\'d expect this method to return true if the <code>Hashtable</code> contained a given key because the key is the primary access mechanism for a <code>Hashtable</code>. The Map interface eliminates this source of confusion by renaming the method <code>containsValue</code>. Also, this improves the interface\'s consistency — <code>containsValue</code> parallels <code>containsKey</code>.</p>\n<blockquote>\n<p><a href="http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html" rel="noreferrer">The Map Interface</a></p>\n</blockquote>\n'}, {'answer_id': 8832544, 'author': 'pwes', 'author_id': 283519, 'author_profile': 'https://Stackoverflow.com/users/283519', 'pm_score': 5, 'selected': False, 'text': '<p>Beside all the other important aspects already mentioned here, Collections API (e.g. Map interface) is being modified all the time to conform to the "latest and greatest" additions to Java spec.</p>\n\n<p>For example, compare Java 5 Map iterating:</p>\n\n<pre><code>for (Elem elem : map.keys()) {\n  elem.doSth();\n}\n</code></pre>\n\n<p>versus the old Hashtable approach:</p>\n\n<pre><code>for (Enumeration en = htable.keys(); en.hasMoreElements(); ) {\n  Elem elem = (Elem) en.nextElement();\n  elem.doSth();\n}\n</code></pre>\n\n<p>In Java 1.8 we are also promised to be able to construct and access HashMaps like in good old scripting languages:</p>\n\n<pre><code>Map&lt;String,Integer&gt; map = { "orange" : 12, "apples" : 15 };\nmap["apples"];\n</code></pre>\n\n<p><strong>Update:</strong> No, they won\'t land in 1.8... :(</p>\n\n<p><a href="https://stackoverflow.com/questions/13692213/are-project-coins-collection-enhancements-going-to-be-in-jdk8">Are Project Coin&#39;s collection enhancements going to be in JDK8?</a></p>\n'}, {'answer_id': 10372667, 'author': 'alain.janinm', 'author_id': 1140748, 'author_profile': 'https://Stackoverflow.com/users/1140748', 'pm_score': 5, 'selected': False, 'text': '<ul>\n<li><p><a href="http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html" rel="noreferrer">HashTable</a> is synchronized, if you are using it in a single thread you can use <a href="http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html" rel="noreferrer">HashMap</a>, which is an unsynchronized version. Unsynchronized objects are often a little more performant. By the way if multiple threads access a HashMap concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. \nYoun can wrap a unsynchronized map in a synchronized one using :</p>\n\n<pre><code>Map m = Collections.synchronizedMap(new HashMap(...));\n</code></pre></li>\n<li><p>HashTable can only contain non-null object as a key or as a value. HashMap can contain one null key and null values.</p></li>\n<li><p>The iterators returned by Map are fail-fast, if the map is structurally modified at any time after the iterator is created, in any way except through the iterator\'s own remove method, the iterator will throw a <code>ConcurrentModificationException</code>. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. <strong>Whereas</strong> the Enumerations returned by Hashtable\'s keys and elements methods are not fail-fast. </p></li>\n<li><p>HashTable and HashMap are member of the <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/collections/index.html" rel="noreferrer">Java Collections Framework</a> (since Java 2 platform v1.2, HashTable was retrofitted to implement the Map interface).</p></li>\n<li><p>HashTable is considered legacy code, the documentation advise to use <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="noreferrer">ConcurrentHashMap</a> in place of Hashtable if a thread-safe highly-concurrent implementation is desired.</p></li>\n<li><p>HashMap doesn\'t guarantee the order in which elements are returned. For HashTable I guess it\'s the same but I\'m not entirely sure, I don\'t find ressource that clearly state that.</p></li>\n</ul>\n'}, {'answer_id': 11883473, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>HashMaps gives you freedom of synchronization and debugging is lot more easier</p>\n'}, {'answer_id': 13467173, 'author': 'Sujan', 'author_id': 819014, 'author_profile': 'https://Stackoverflow.com/users/819014', 'pm_score': 6, 'selected': False, 'text': '<p>Take a look at this chart. It provides comparisons between different data structures along with <code>HashMap</code> and <code>Hashtable</code>. The comparison is precise, clear and easy to understand.</p>\n\n<p><a href="https://docs.google.com/spreadsheet/pub?key=0Aq3e8BiuZY2wdFpHSlV0QzVmV1lUNHJidGd2b0Zrb3c&amp;single=true&amp;gid=0&amp;output=pdf" rel="noreferrer">Java Collection Matrix</a></p>\n'}, {'answer_id': 13797704, 'author': 'SkyWalker', 'author_id': 1142881, 'author_profile': 'https://Stackoverflow.com/users/1142881', 'pm_score': 5, 'selected': False, 'text': '<p><code>HashMap</code> and <code>Hashtable</code> have significant algorithmic differences as well. No one has mentioned this before so that\'s why I am bringing it up. <code>HashMap</code> will construct a hash table with power of two size, increase it dynamically such that you have at most about eight elements (collisions) in any bucket and will stir the elements very well for general element types. However, the <code>Hashtable</code> implementation provides better and finer control over the hashing if you know what you are doing, namely you can fix the table size using e.g. the closest prime number to your values domain size and this will result in better performance than HashMap i.e. less collisions for some cases.</p>\n\n<p>Separate from the obvious differences discussed extensively in this question, I see the Hashtable as a "manual drive" car where you have better control over the hashing and the HashMap as the "automatic drive" counterpart that will generally perform well.</p>\n'}, {'answer_id': 14452144, 'author': 'raja', 'author_id': 1199342, 'author_profile': 'https://Stackoverflow.com/users/1199342', 'pm_score': 4, 'selected': False, 'text': "<ol>\n<li><code>Hashtable</code> is synchronized whereas <code>HashMap</code> is not.</li>\n<li>Another difference is that iterator in the <code>HashMap</code> is fail-safe\nwhile the enumerator for the <code>Hashtable</code> isn't. If you change the map\nwhile iterating, you'll know.</li>\n<li><code>HashMap</code> permits null values in it, while <code>Hashtable</code> doesn't.</li>\n</ol>\n"}, {'answer_id': 14627155, 'author': 'Ankit', 'author_id': 1203455, 'author_profile': 'https://Stackoverflow.com/users/1203455', 'pm_score': 4, 'selected': False, 'text': '<p>HashMap: It is a class available inside java.util package and it is used to store the element in key and value format.</p>\n\n<p>Hashtable: It is a legacy class which is being recognized inside collection framework.</p>\n'}, {'answer_id': 16018266, 'author': 'jontejj', 'author_id': 541755, 'author_profile': 'https://Stackoverflow.com/users/541755', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html" rel="noreferrer">HashTable</a> is a legacy class in the jdk that shouldn\'t be used anymore. Replace usages of it with <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="noreferrer">ConcurrentHashMap</a>. If you don\'t require thread safety, use <a href="http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html" rel="noreferrer">HashMap</a> which isn\'t <a href="http://jsr-305.googlecode.com/svn/trunk/javadoc/javax/annotation/concurrent/ThreadSafe.html" rel="noreferrer">threadsafe</a> but faster and uses less memory.</p>\n'}, {'answer_id': 17651399, 'author': 'pong', 'author_id': 1162526, 'author_profile': 'https://Stackoverflow.com/users/1162526', 'pm_score': 3, 'selected': False, 'text': '<p><code>HashMap</code> is emulated and therefore usable in <code>GWT client code</code> whereas <code>Hashtable</code> is not.</p>\n'}, {'answer_id': 17815037, 'author': 'Ekanta Swain', 'author_id': 2476998, 'author_profile': 'https://Stackoverflow.com/users/2476998', 'pm_score': 2, 'selected': False, 'text': "<p>HashMap is a class  used to store the element in key and value format.it is not thread safe.\nbecause it is not synchronized .where as Hashtable is synchronized.Hashmap permits null but hastable doesn't permit null.</p>\n"}, {'answer_id': 20519518, 'author': 'user1923551', 'author_id': 1923551, 'author_profile': 'https://Stackoverflow.com/users/1923551', 'pm_score': 4, 'selected': False, 'text': "<p>There are 5 basic differentiations with HashTable and HashMaps. </p>\n\n<ol>\n<li>Maps allows you to iterate and retrieve keys, values, and both key-value pairs as well, Where HashTable don't have all this capability. </li>\n<li>In Hashtable there is a function contains(), which is very confusing to use. Because the meaning of contains is slightly deviating. Whether it means contains key or contains  value? tough to understand. Same thing in Maps we have ContainsKey() and ContainsValue() functions, which are very easy to understand. </li>\n<li>In hashmap you can remove element while iterating, safely. where as it is not possible in hashtables.</li>\n<li>HashTables are by default synchronized, so it can be used with multiple threads easily. Where as HashMaps are not synchronized by default, so can be used with only single thread.  But you can still convert HashMap to synchronized by using Collections util class's synchronizedMap(Map m) function.</li>\n<li>HashTable won't allow null keys or null values. Where as HashMap allows one null key, and multiple null values.</li>\n</ol>\n"}, {'answer_id': 22253585, 'author': 'PetarMI', 'author_id': 2970123, 'author_profile': 'https://Stackoverflow.com/users/2970123', 'pm_score': 3, 'selected': False, 'text': "<p>Since Hashtable in Java is a subclass of Dictionary class which is now obsolete due to the existence of Map Interface, it is not used anymore. Moreover, there isn't anything you can't do with a class that implements the Map Interface that you can do with a Hashtable. </p>\n"}, {'answer_id': 22491742, 'author': 'Shreyos Adikari', 'author_id': 838841, 'author_profile': 'https://Stackoverflow.com/users/838841', 'pm_score': 4, 'selected': False, 'text': '<p>My small contribution :</p>\n<blockquote>\n<ol>\n<li><p>First and most significant different between <code>Hashtable</code> and <code>HashMap</code> is that, <code>HashMap</code> is not thread-safe  while <code>Hashtable</code> is a thread-safe collection.</p>\n</li>\n<li><p>Second important difference between <code>Hashtable</code> and <code>HashMap</code> is performance, since <code>HashMap</code> is not synchronized it perform better than <code>Hashtable</code>.</p>\n</li>\n<li><p>Third difference on <code>Hashtable</code> vs <code>HashMap</code> is that <code>Hashtable</code> is obsolete class and you should be using <code>ConcurrentHashMap</code> in place of <code>Hashtable</code> in Java.</p>\n</li>\n</ol>\n</blockquote>\n'}, {'answer_id': 22629569, 'author': 'pierrotlefou', 'author_id': 115722, 'author_profile': 'https://Stackoverflow.com/users/115722', 'pm_score': 7, 'selected': False, 'text': '<p>Keep in mind that <code>HashTable</code> was legacy class before Java Collections Framework (JCF) was introduced and was later retrofitted to implement the <code>Map</code> interface. So was <code>Vector</code> and <code>Stack</code>. </p>\n\n<p><strong>Therefore, always stay away from them in new code since there always better alternative in the JCF</strong> as others had pointed out.</p>\n\n<p>Here is the <a href="http://pierrchen.blogspot.com/2014/03/java-collections-framework-cheat-sheet.html" rel="noreferrer">Java collection cheat sheet</a> that you will find useful. Notice the gray block contains the legacy class HashTable,Vector and Stack.</p>\n\n<p><img src="https://i.stack.imgur.com/PyflH.png" alt="enter image description here"></p>\n'}, {'answer_id': 24583680, 'author': 'JegsVala', 'author_id': 3230563, 'author_profile': 'https://Stackoverflow.com/users/3230563', 'pm_score': 3, 'selected': False, 'text': '<p><strong>HashMap and HashTable</strong>    </p>\n\n<ul>\n<li>Some important points about HashMap and HashTable.\n   please read below details.</li>\n</ul>\n\n<p>1) Hashtable and Hashmap implement the java.util.Map interface\n2) Both Hashmap and Hashtable is the hash based collection. and working on hashing.\nso these are similarity of HashMap and HashTable.    </p>\n\n<ul>\n<li>What is the difference between HashMap and HashTable?</li>\n</ul>\n\n<p>1) First difference is HashMap is not thread safe While HashTable is ThreadSafe<br>\n2) HashMap is performance wise better because it is not thread safe. while Hashtable performance wise is not better because it is thread safe. so multiple thread can not access Hashtable at the same time.</p>\n'}, {'answer_id': 25348157, 'author': 'Night0', 'author_id': 2647077, 'author_profile': 'https://Stackoverflow.com/users/2647077', 'pm_score': 3, 'selected': False, 'text': '<p>Old and classic topic, just want to add this helpful blog that explains this:</p>\n\n<p><a href="http://blog.manishchhabra.com/2012/08/the-5-main-differences-betwen-hashmap-and-hashtable/" rel="noreferrer">http://blog.manishchhabra.com/2012/08/the-5-main-differences-betwen-hashmap-and-hashtable/</a></p>\n\n<p>Blog by Manish Chhabra</p>\n\n<blockquote>\n  <p>The 5 main differences betwen HashMap and Hashtable</p>\n  \n  <p>HashMap and Hashtable both implement java.util.Map interface but there\n  are some differences that Java developers must understand to write\n  more efficient code. As of the Java 2 platform v1.2, Hashtable class\n  was retrofitted to implement the Map interface, making it a member of\n  the Java Collections Framework.</p>\n  \n  <ol>\n  <li><p>One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which\n  means Hashtable is thread-safe and can be shared between multiple\n  threads but HashMap cannot be shared between multiple threads without\n  proper synchronization. Java 5 introduced ConcurrentHashMap which is\n  an alternative of Hashtable and provides better scalability than\n  Hashtable in Java.Synchronized means only one thread can modify a hash\n  table at one point of time. Basically, it means that any thread before\n  performing an update on a hashtable will have to acquire a lock on the\n  object while others will wait for lock to be released.</p></li>\n  <li><p>The HashMap class is roughly equivalent to Hashtable, except that it permits nulls. (HashMap allows null values as key and value whereas\n  Hashtable doesn’t allow nulls).</p></li>\n  <li><p>The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the\n  enumerator for the Hashtable is not and throw\n  ConcurrentModificationException if any other Thread modifies the map\n  structurally by adding or removing any element except Iterator’s own\n  remove() method. But this is not a guaranteed behavior and will be\n  done by JVM on best effort. This is also an important difference\n  between Enumeration and Iterator in Java.</p></li>\n  <li><p>One more notable difference between Hashtable and HashMap is that because of thread-safety and synchronization Hashtable is much slower\n  than HashMap if used in Single threaded environment. So if you don’t\n  need synchronization and HashMap is only used by one thread, it out\n  perform Hashtable in Java.</p></li>\n  <li><p>HashMap does not guarantee that the order of the map will remain constant over time.</p></li>\n  </ol>\n  \n  <p>Note that HashMap can be synchronized by</p>\n\n<pre><code>Map m = Collections.synchronizedMap(hashMap);\n</code></pre>\n  \n  <p>In Summary there are significant differences between Hashtable and\n  HashMap in Java e.g. thread-safety and speed and based upon that only\n  use Hashtable if you absolutely need thread-safety, if you are running\n  Java 5 consider using ConcurrentHashMap in Java.</p>\n</blockquote>\n'}, {'answer_id': 25526024, 'author': 'Rahul Tripathi', 'author_id': 3981269, 'author_profile': 'https://Stackoverflow.com/users/3981269', 'pm_score': 4, 'selected': False, 'text': "<p>1.<code>Hashmap</code> and <code>HashTable</code> both store key and value. </p>\n\n<p>2.<code>Hashmap</code> can store one key as <code>null</code>. <code>Hashtable</code> can't store <code>null</code>.</p>\n\n<p>3.<code>HashMap</code> is not synchronized but <code>Hashtable</code> is synchronized. </p>\n\n<p>4.<code>HashMap</code> can be synchronized with <code>Collection.SyncronizedMap(map)</code></p>\n\n<pre><code>Map hashmap = new HashMap();\n\nMap map = Collections.SyncronizedMap(hashmap);\n</code></pre>\n"}, {'answer_id': 28426488, 'author': 'IntelliJ Amiya', 'author_id': 3395198, 'author_profile': 'https://Stackoverflow.com/users/3395198', 'pm_score': 3, 'selected': False, 'text': '<p><strong><code>Hashtable:</code></strong></p>\n\n<p><strong>Hashtable</strong> is a data structure that retains values of key-value pair. It doesn’t allow null for both the keys and the values. You will get a <code>NullPointerException</code> if you add null value. It is synchronized. So it comes with its cost. Only one thread can access <strong>HashTable</strong> at a particular time.</p>\n\n<p><strong>Example</strong> :</p>\n\n<pre><code>import java.util.Map;\nimport java.util.Hashtable;\n\npublic class TestClass {\n\n    public static void main(String args[ ]) {\n    Map&lt;Integer,String&gt; states= new Hashtable&lt;Integer,String&gt;();\n    states.put(1, "INDIA");\n    states.put(2, "USA");\n\n    states.put(3, null);    //will throw NullPointerEcxeption at runtime\n\n    System.out.println(states.get(1));\n    System.out.println(states.get(2));\n//  System.out.println(states.get(3));\n\n    }\n}\n</code></pre>\n\n<p><strong>HashMap:</strong></p>\n\n<p><strong>HashMap</strong> is like <strong>Hashtable</strong> but it also accepts key value pair. It allows null for both the keys and the values. Its performance better is better than <code>HashTable</code>, because it is <code>unsynchronized</code>.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\n\npublic class TestClass {\n\n    public static void main(String args[ ]) {\n    Map&lt;Integer,String&gt; states = new HashMap&lt;Integer,String&gt;();\n    states.put(1, "INDIA");\n    states.put(2, "USA");\n\n    states.put(3, null);    // Okay\n    states.put(null,"UK");\n\n    System.out.println(states.get(1));\n    System.out.println(states.get(2));\n    System.out.println(states.get(3));\n\n    }\n}\n</code></pre>\n'}, {'answer_id': 34618895, 'author': 'amitguptageek', 'author_id': 3527383, 'author_profile': 'https://Stackoverflow.com/users/3527383', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Synchronization or Thread Safe</strong> :</p>\n\n<p>Hash Map is not synchronized hence it is not thred safe and it cannot be shared between multiple threads without proper synchronized block whereas, Hashtable is synchronized and hence it is thread safe.</p>\n\n<p><strong>Null keys and null values</strong> :</p>\n\n<p>HashMap allows one null key and any number of null values.Hashtable does not allow null keys or values. </p>\n\n<p><strong>Iterating the values</strong>:</p>\n\n<p>Iterator in the HashMap is a fail-fast iterator 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.</p>\n\n<p><strong>Superclass and Legacy</strong> :</p>\n\n<p>HashMap is subclass of AbstractMap class whereas Hashtable is subclass of Dictionary class.</p>\n\n<p><strong>Performance</strong> :</p>\n\n<p>As HashMap is not synchronized it is faster as compared to Hashtable.</p>\n\n<p>Refer <a href="http://modernpathshala.com/Article/1020/difference-between-hashmap-and-hashtable-in-java" rel="nofollow">http://modernpathshala.com/Article/1020/difference-between-hashmap-and-hashtable-in-java</a> for examples and interview questions and quiz related to  Java collection</p>\n'}, {'answer_id': 37031553, 'author': 'Kostas Kryptos', 'author_id': 3294902, 'author_profile': 'https://Stackoverflow.com/users/3294902', 'pm_score': 4, 'selected': False, 'text': '<p>Apart from the differences already mentioned, it should be noted that since Java 8, <code>HashMap</code> 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 <em>when searching</em> is</p>\n\n<p>O(log(n)) for <code>HashMap</code> <strong>Vs</strong> O(n) in <code>Hashtable</code>.</p>\n\n<p>*The aforementioned improvement has not been applied to <code>Hashtable</code> yet, but only to <code>HashMap</code>, <code>LinkedHashMap</code>, and <code>ConcurrentHashMap</code>.</p>\n\n<p>FYI, currently,</p>\n\n<ul>\n<li><code>TREEIFY_THRESHOLD = 8</code> : if a bucket contains more than 8 nodes, the linked list is transformed into a balanced tree.</li>\n<li><code>UNTREEIFY_THRESHOLD = 6</code> : when a bucket becomes too small (due to removal or resizing) the tree is converted back to linked list.</li>\n</ul>\n'}, {'answer_id': 42622789, 'author': 'roottraveller', 'author_id': 5167682, 'author_profile': 'https://Stackoverflow.com/users/5167682', 'pm_score': 7, 'selected': False, 'text': '<p>There are many good answers already posted. I\'m adding few new points and summarizing it.</p>\n<p><code>HashMap</code> and <code>Hashtable</code> both are used to store <em>data in key and value form</em>. Both are using hashing technique to store unique keys.\nBut there are many differences between HashMap and Hashtable classes that are given below.</p>\n<p><strong>HashMap</strong></p>\n<ol>\n<li><code>HashMap</code> is non synchronized. It is not-thread safe and can\'t be shared between many threads without proper synchronization code.</li>\n<li><code>HashMap</code> allows one null key and multiple null values.</li>\n<li><code>HashMap</code> is a new class introduced in JDK 1.2.</li>\n<li><code>HashMap</code> is fast.</li>\n<li>We can make the <code>HashMap</code> as synchronized by calling this code<br />\n<code>Map m = Collections.synchronizedMap(HashMap);  </code></li>\n<li><code>HashMap</code> is traversed by Iterator.</li>\n<li>Iterator in <code>HashMap</code> is fail-fast.</li>\n<li><code>HashMap</code> inherits AbstractMap class.</li>\n</ol>\n<p><strong>Hashtable</strong></p>\n<ol>\n<li><code>Hashtable</code> is synchronized. It is thread-safe and can be shared with many threads.</li>\n<li><code>Hashtable</code> doesn\'t allow null key or value.</li>\n<li><code>Hashtable</code> is a legacy class.</li>\n<li><code>Hashtable</code> is slow.</li>\n<li><code>Hashtable</code> is internally synchronized and can\'t be unsynchronized.</li>\n<li><code>Hashtable</code> is traversed by Enumerator and Iterator.</li>\n<li>Enumerator in <code>Hashtable</code> is not fail-fast.</li>\n<li><code>Hashtable</code> inherits Dictionary class.</li>\n</ol>\n<p>Further reading <a href="http://javarevisited.blogspot.in/2010/10/difference-between-hashmap-and.html" rel="noreferrer">What is difference between HashMap and Hashtable in Java?</a></p>\n<p><a href="https://i.stack.imgur.com/sDoih.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sDoih.png" alt="enter image description here" /></a></p>\n'}, {'answer_id': 43546846, 'author': 'KIBOU Hassan', 'author_id': 4226914, 'author_profile': 'https://Stackoverflow.com/users/4226914', 'pm_score': 0, 'selected': False, 'text': '<p>The Hashtable class is synchronized, that is, it is designed to be used by applications that handle multiple or multithreaded process. Synchronized classes are less efficient in the classical case of an application to a process, so the Hashmap class is faster in general.\nThe HashTable class does not accept the Null value, either for keys or for values, while the HashMap class allows a single key with Null and as many as null as possible.</p>\n'}, {'answer_id': 48094803, 'author': 'Yash', 'author_id': 5081877, 'author_profile': 'https://Stackoverflow.com/users/5081877', 'pm_score': 5, 'selected': False, 'text': '<p><em>A <a href="https://docs.oracle.com/javase/tutorial/collections/intro/index.html" rel="noreferrer"><code>Collection</code></a> — sometimes called a container — is simply an object that groups multiple elements into a single unit. <code>Collection</code>s are used to store, retrieve, manipulate, and communicate aggregate data. A collections framework <sup><a href="https://en.wikipedia.org/wiki/Java_collections_framework" rel="noreferrer">W</a></sup> is a unified architecture for representing and manipulating collections.</em></p>\n<p>The <code>HashMap</code> <sup><a href="https://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html" rel="noreferrer"><em><code>JDK1.2</code></em></a></sup> and Hashtable <sup><a href="https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html" rel="noreferrer"><em><code>JDK1.0</code></em></a></sup>, both are used to represent a group of objects that are represented in <code>&lt;Key, Value&gt;</code> pair. Each <code>&lt;Key, Value&gt;</code> pair is called <code>Entry</code> object. The collection of Entries is referred by the object of <code>HashMap</code> and <code>Hashtable</code>. Keys in a collection must be unique or distinctive. [as they are used to retrieve a mapped value a particular key. values in a collection can be duplicated.]</p>\n<hr />\n<p><strong>«</strong> <strong>Superclass, Legacy and Collection Framework member</strong></p>\n<p><em>Hashtable is a legacy class introduced in <code>JDK1.0</code>, which is a subclass of Dictionary class. From <code>JDK1.2</code> Hashtable is re-engineered to implement the <a href="https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html" rel="noreferrer">Map interface</a> to make a member of collection framework. HashMap is a member of Java Collection Framework right from the beginning of its introduction in <code>JDK1.2</code>. HashMap is the subclass of the AbstractMap class.</em></p>\n\n<pre class="lang-java prettyprint-override"><code>public class Hashtable&lt;K,V&gt; extends Dictionary&lt;K,V&gt; implements Map&lt;K,V&gt;, Cloneable, Serializable { ... }\n\npublic class HashMap&lt;K,V&gt; extends AbstractMap&lt;K,V&gt; implements Map&lt;K,V&gt;, Cloneable, Serializable { ... }\n</code></pre>\n\n<p><strong>«</strong> <strong>Initial capacity and Load factor</strong></p>\n<p><em>The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a &quot;<code>hash </code><a href="http://www.algolist.net/Data_structures/Hash_table/Chaining" rel="noreferrer"><code>collision</code></a>&quot;, a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.</em></p>\n<p><em>HashMap constructs an empty hash table with the default initial capacity <strong>(16)</strong> and the default load factor (0.75). Where as Hashtable constructs empty hashtable with a default initial capacity <strong>(11)</strong> and load factor/fill ratio (0.75).</em></p>\n<p><a href="https://i.stack.imgur.com/AerdR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AerdR.png" alt="Hash Map &amp; Hashtable" /></a></p>\n<p><strong>«</strong> <strong>Structural modification in case of hash collision</strong></p>\n<p><em><code>HashMap</code>, <code>Hashtable</code> in case of hash collisions they store the map entries in linked lists. <strong>From Java8 for <code>HashMap</code></strong> if hash bucket grows beyond a certain threshold, that bucket will switch from <a href="http://openjdk.java.net/jeps/180" rel="noreferrer"><code>linked list of entries to a balanced tree</code></a>. which improve worst-case performance from O(n) to O(log n). While converting the list to binary tree, hashcode is used as a branching variable. If there are two different hashcodes in the same bucket, one is considered bigger and goes to the right of the tree and other one to the left. But when both the hashcodes are equal, <code>HashMap</code> assumes that the keys are comparable, and compares the key to determine the direction so that some order can be maintained. It is a good practice to make the keys of <code>HashMap</code> <a href="https://stackoverflow.com/a/31244596/5081877">comparable</a>. On adding entries if bucket size reaches <code>TREEIFY_THRESHOLD = 8</code> convert linked list of entries to a balanced tree, on removing entries less than <code>TREEIFY_THRESHOLD</code>  and at most <code>UNTREEIFY_THRESHOLD = 6</code> will reconvert  balanced tree to linked list of entries. <sup><a href="http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/HashMap.java#l244" rel="noreferrer">Java 8 SRC</a>, <a href="https://stackoverflow.com/a/43911638/5081877">stackpost</a></sup></em></p>\n<p><strong>«</strong> <strong>Collection-view iteration, Fail-Fast and Fail-Safe</strong></p>\n<pre class="lang-java prettyprint-override"><code>    +--------------------+-----------+-------------+\n    |                    | Iterator  | Enumeration |\n    +--------------------+-----------+-------------+\n    | Hashtable          | fail-fast |    safe     |\n    +--------------------+-----------+-------------+\n    | HashMap            | fail-fast | fail-fast   |\n    +--------------------+-----------+-------------+\n    | ConcurrentHashMap  |   safe    |   safe      |\n    +--------------------+-----------+-------------+\n</code></pre>\n<p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html" rel="noreferrer"><code>Iterator</code></a> is a fail-fast in nature. i.e it throws ConcurrentModificationException if a collection is modified while iterating other than it’s own remove() method. Where as <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html" rel="noreferrer"><code>Enumeration</code></a> is fail-safe in nature. It doesn’t throw any exceptions if a collection is modified while iterating.</p>\n<p>According to Java API Docs, Iterator is always preferred over the Enumeration.</p>\n<p><sub><b>NOTE:</b> The functionality of Enumeration interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names. New implementations should consider using Iterator in preference to Enumeration.</sub></p>\n<p>In <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/collections/changes5.html" rel="noreferrer">Java 5 introduced ConcurrentMap Interface</a>: <code>ConcurrentHashMap</code> - a highly concurrent, high-performance <code>ConcurrentMap</code> implementation backed by a hash table. This implementation never blocks when performing retrievals and allows the client to select the concurrency level for updates. It is intended as a drop-in replacement for <code>Hashtable</code>: in addition to implementing <code>ConcurrentMap</code>, it supports all of the &quot;legacy&quot; methods peculiar to <code>Hashtable</code>.</p>\n<ul>\n<li><p>Each <code>HashMapEntry</code>s value is <a href="https://stackoverflow.com/a/47695757/5081877">volatile</a> thereby ensuring fine grain consistency for contended modifications and subsequent reads; each read reflects the most recently completed update</p>\n</li>\n<li><p>Iterators and Enumerations are Fail Safe - reflecting the state at some point since the creation of iterator/enumeration; this allows for simultaneous reads and modifications at the cost of reduced consistency. They do not throw ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time.</p>\n</li>\n<li><p><strong><em>Like <code>Hashtable</code> but unlike <code>HashMap</code>, this class does not allow null to be used as a key or value.</em></strong></p>\n</li>\n</ul>\n\n<pre class="lang-java prettyprint-override"><code>public static void main(String[] args) {\n\n    //HashMap&lt;String, Integer&gt; hash = new HashMap&lt;String, Integer&gt;();\n    Hashtable&lt;String, Integer&gt; hash = new Hashtable&lt;String, Integer&gt;();\n    //ConcurrentHashMap&lt;String, Integer&gt; hash = new ConcurrentHashMap&lt;&gt;();\n    \n    new Thread() {\n        @Override public void run() {\n            try {\n                for (int i = 10; i &lt; 20; i++) {\n                    sleepThread(1);\n                    System.out.println(&quot;T1 :- Key&quot;+i);\n                    hash.put(&quot;Key&quot;+i, i);\n                }\n                System.out.println( System.identityHashCode( hash ) );\n            } catch ( Exception e ) {\n                e.printStackTrace();\n            }\n        }\n    }.start();\n    new Thread() {\n        @Override public void run() {\n            try {\n                sleepThread(5);\n                // ConcurrentHashMap  traverse using Iterator, Enumeration is Fail-Safe.\n                \n                // Hashtable traverse using Enumeration is Fail-Safe, Iterator is Fail-Fast.\n                for (Enumeration&lt;String&gt; e = hash.keys(); e.hasMoreElements(); ) {\n                    sleepThread(1);\n                    System.out.println(&quot;T2 : &quot;+ e.nextElement());\n                }\n                \n                // HashMap traverse using Iterator, Enumeration is Fail-Fast.\n                /*\n                for (Iterator&lt; Entry&lt;String, Integer&gt; &gt; it = hash.entrySet().iterator(); it.hasNext(); ) {\n                    sleepThread(1);\n                    System.out.println(&quot;T2 : &quot;+ it.next());\n                    // ConcurrentModificationException at java.util.Hashtable$Enumerator.next\n                }\n                */\n                \n                /*\n                Set&lt; Entry&lt;String, Integer&gt; &gt; entrySet = hash.entrySet();\n                Iterator&lt; Entry&lt;String, Integer&gt; &gt; it = entrySet.iterator();\n                Enumeration&lt;Entry&lt;String, Integer&gt;&gt; entryEnumeration = Collections.enumeration( entrySet );\n                while( entryEnumeration.hasMoreElements() ) {\n                    sleepThread(1);\n                    Entry&lt;String, Integer&gt; nextElement = entryEnumeration.nextElement();\n                    System.out.println(&quot;T2 : &quot;+ nextElement.getKey() +&quot; : &quot;+ nextElement.getValue() );\n                    //java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextNode\n                    //                                          at java.util.HashMap$EntryIterator.next\n                    //                                          at java.util.Collections$3.nextElement\n                }\n                */\n            } catch ( Exception e ) {\n                e.printStackTrace();\n            }\n        }\n    }.start();\n    \n    Map&lt;String, String&gt; unmodifiableMap = Collections.unmodifiableMap( map );\n    try {\n        unmodifiableMap.put(&quot;key4&quot;, &quot;unmodifiableMap&quot;);\n    } catch (java.lang.UnsupportedOperationException e) {\n        System.err.println(&quot;UnsupportedOperationException : &quot;+ e.getMessage() );\n    }\n}\nstatic void sleepThread( int sec ) {\n    try {\n        Thread.sleep( 1000 * sec );\n    } catch (InterruptedException e) {\n        e.printStackTrace();\n    }\n}\n</code></pre>\n\n<p><strong>«</strong> <strong>Null Keys And Null Values</strong></p>\n<p><code>HashMap</code> allows maximum one null key and any number of null values. Where as <code>Hashtable</code> doesn’t allow even a single null key and null value, if the key or value null is then it throws NullPointerException. <sup><a href="https://stackoverflow.com/a/31243387/5081877">Example</a></sup></p>\n<p><strong>«</strong> <strong>Synchronized, Thread Safe</strong></p>\n<p><code>Hashtable</code> is internally synchronized. Therefore, it is very much safe to use <code>Hashtable</code> in multi threaded applications. Where as <code>HashMap</code> is not internally synchronized. Therefore, it is not safe to use <code>HashMap</code> in multi threaded applications without external synchronization. You can externally synchronize <code>HashMap</code> using <code>Collections.synchronizedMap()</code> method.</p>\n<p><strong>«</strong> <strong>Performance</strong></p>\n<p>As <code>Hashtable</code> is internally synchronized, this makes <code>Hashtable</code> slightly slower than the <code>HashMap</code>.</p>\n<hr />\n<p>@See</p>\n<ul>\n<li><a href="https://en.wikipedia.org/wiki/Red%E2%80%93black_tree" rel="noreferrer">A red–black tree is a kind of self-balancing binary search tree</a></li>\n<li><a href="https://www.nagarro.com/de/perspectives/post/24/performance-improvement-for-hashmap-in-java-8" rel="noreferrer">Performance Improvement for <code>HashMap</code> in Java 8</a></li>\n</ul>\n'}, {'answer_id': 58624450, 'author': 'DeC', 'author_id': 7888956, 'author_profile': 'https://Stackoverflow.com/users/7888956', 'pm_score': 3, 'selected': False, 'text': '<p><strong>HashMap</strong> and <strong>Hashtable</strong> both are used to store data in key and value form. Both are using hashing technique to store unique keys.\nut there are many differences between HashMap and Hashtable classes that are given below.</p>\n\n<p><a href="https://i.stack.imgur.com/mLpKn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mLpKn.png" alt="enter image description here"></a></p>\n'}]
['https://Stackoverflow.com/questions/40471', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4316/']