Differences between HashMap and Hashtable?












3297














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



Which is more efficient for non-threaded applications?










share|improve this question




















  • 5




    HashTable is obsolete in Java 1.7 and it is recommended to use ConcurrentMap implementation
    – MissFiona
    Apr 9 '17 at 22:10
















3297














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



Which is more efficient for non-threaded applications?










share|improve this question




















  • 5




    HashTable is obsolete in Java 1.7 and it is recommended to use ConcurrentMap implementation
    – MissFiona
    Apr 9 '17 at 22:10














3297












3297








3297


1192





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



Which is more efficient for non-threaded applications?










share|improve this question















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



Which is more efficient for non-threaded applications?







java collections hashmap hashtable






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 21 '18 at 12:13









Andrey Tyukin

27k42349




27k42349










asked Sep 2 '08 at 20:12









dmanxiii

20k92823




20k92823








  • 5




    HashTable is obsolete in Java 1.7 and it is recommended to use ConcurrentMap implementation
    – MissFiona
    Apr 9 '17 at 22:10














  • 5




    HashTable is obsolete in Java 1.7 and it is recommended to use ConcurrentMap implementation
    – MissFiona
    Apr 9 '17 at 22:10








5




5




HashTable is obsolete in Java 1.7 and it is recommended to use ConcurrentMap implementation
– MissFiona
Apr 9 '17 at 22:10




HashTable is obsolete in Java 1.7 and it is recommended to use ConcurrentMap implementation
– MissFiona
Apr 9 '17 at 22:10












34 Answers
34






active

oldest

votes













1 2
next












3362














There are several differences between HashMap and Hashtable in Java:




  1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.


  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.


  3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.



Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.






share|improve this answer



















  • 52




    If you want to make a HashMap thread-safe, use Collections.synchronizedMap().
    – Rok Strniša
    Nov 22 '11 at 18:48






  • 213




    I would also comment that the naive approach to thread-safety in Hashtable ("synchronizing every method should take care of any concurrency problems!") makes it very much worse for threaded applications. You're better off externally synchronizing a HashMap (and thinking about the consequences), or using a ConcurrentMap implementation (and exploiting its extended API for concurrency). Bottom line: the only reason to use Hashtable is when a legacy API (from ca. 1996) requires it.
    – erickson
    Mar 16 '12 at 17:19






  • 6




    HashMap gives flexibility to programmer to write threadSafe code when they actually use it. It happened rarely that I needed a thread safe collection like ConcurrentHashMap or HashTable. What I needed is certain set of functions or certain statements in a synchronized block to be threadsafe.
    – Gaurava Agarwal
    Jun 27 '16 at 9:00












  • Hashtable is obsolete and we are using HashMap for non thread safe environment. If you need thread safety then you can use Collections.synchronizedMap() or use ConcurrentHashMap which is more efficient that hashtable.
    – Maneesh Kumar
    Mar 30 '18 at 3:45










  • It's obsolete but not deprecated and I'm wondering why this is. I'm guessing removing this class (and Vector for the same reasons) would break too much existing code and annotating with @Deprecated would imply an intention to remove the code, which apparently is not there.
    – Jilles van Gurp
    May 19 '18 at 8:11



















610














Note, that a lot of the answers state that Hashtable is synchronised. In practice this buys you very little. 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 synchronisation.



A very common idiom is to "check then put" - i.e. look for an entry in the Map, and add it if it does not already exist. This is not in any way an atomic operation whether you use Hashtable or HashMap.



An equivalently synchronised HashMap can be obtained by:



Collections.synchronizedMap(myMap);


But to correctly implement this logic you need additional synchronisation of the form:



synchronized(myMap) {
if (!myMap.containsKey("tomato"))
myMap.put("tomato", "red");
}


Even iterating over a Hashtable's entries (or a HashMap obtained by Collections.synchronizedMap) is not thread safe unless you also guard the Map from being modified through additional synchronization.



Implementations of the ConcurrentMap interface (for example ConcurrentHashMap) solve some of this by including thread safe check-then-act semantics such as:



ConcurrentMap.putIfAbsent(key, value);





share|improve this answer



















  • 46




    Also note that if a HashMap is modified, iterators pointing to it are rendered invalid.
    – Chris K
    Apr 22 '09 at 22:03






  • 18




    Iterator will throw ConcurrentModificationException, right?
    – Bhushan
    Jun 30 '11 at 2:26






  • 3




    So is there any difference between synchronized(myMap) {...} and ConcurrentHashMap in terms of thread safe?
    – telebog
    Nov 11 '11 at 16:48








  • 3




    Very true, I tried to explain same here..lovehasija.com/2012/08/16/…
    – Love Hasija
    Sep 20 '12 at 10:21












  • @Bhushan: It will throw on a best-effort basis, this is not guaranteed behavior: docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
    – Matt Stephenson
    Oct 3 '13 at 18:49



















310














Hashtable is considered legacy code. There's nothing about Hashtable that can't be done using HashMap or derivations of HashMap, so for new code, I don't see any justification for going back to Hashtable.






share|improve this answer



















  • 92




    From Hashtable javadoc (emphasis added): "As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework." However, you are right that it is legacy code. All the benefits of synchronization can be obtained more efficiently with Collections.synchronizedMap(HashMap). (Similar to Vector being a legacy version of Collections.synchronizedList(ArrayList).)
    – Kip
    Jan 19 '10 at 22:09






  • 15




    @aberrant80: unfortunately you have no choice between the two and have to use Hashtable when programming for J2ME...
    – pwes
    Jan 12 '12 at 8:13






  • 5




    this answer should be deleted. it contains incorrect information and has a lot of upvotes.
    – anon58192932
    Jan 22 '16 at 20:40










  • @anon58192932 Is it possible to edit the question to fix it?
    – GC_
    Oct 14 '16 at 15:39








  • 1




    We have to get the attention of the poster @aberrant80 or an admin by flagging. Flagging could help - will try that now.
    – anon58192932
    Oct 14 '16 at 20:05



















157














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 from 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







share|improve this answer



















  • 18




    This answer contains at least 2 significant factual inaccuracies. It certainly DOES NOT deserve this many upvotes.
    – Stephen C
    Sep 9 '13 at 8:05






  • 55




    1) HashMap's iterators are NOT fail-safe. They are fail-fast. There is a huge difference in meaning between those two terms. 2) There is no set operation on a HashMap. 3) The put(...) operation won't throw IllegalArgumentException if there was a previous change. 4) The fail-fast behaviour of HashMap also occurs if you change a mapping. 5) The fail-fast behaviour is guaranteed. (What is not guaranteed is the behaviour of a HashTable if you make a concurrent modification. The actual behaviour is ... unpredictable.)
    – Stephen C
    Sep 9 '13 at 8:14






  • 24




    6) Hashtable does not guarantee that the order of map elements will be stable over time either. (You are perhaps confusing Hashtable with LinkedHashMap.)
    – Stephen C
    Sep 9 '13 at 8:16






  • 3




    Anyone else really worried that students these days are getting the errant idea that getting "synchronized versions" of the collections somehow means that you don't have to externally synchronize compound operations? My favorite example of this being thing.set(thing.get() + 1); which more often than not catches newbies by surprise as completely unprotected, especially if the get() and set() are synchronized methods. Many of them are expecting magic.
    – user4229245
    May 4 '15 at 22:26












  • Iterators on HashMap is not fail-safe
    – Abdul
    Jul 30 '18 at 1:56



















113














HashMap: An implementation of the Map interface that uses hash codes to index an array.
Hashtable: Hi, 1998 called. They want their collections API back.



Seriously though, you're better off staying away from Hashtable 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 ConcurrentHashMap instead.






share|improve this answer























  • This actually makes sense. ConcurrentHashMaps gives you freedom of synchronization and debugging is lot more easier.
    – prap19
    Nov 19 '11 at 14:55






  • 1




    Is this specific to Java or all the hash map implementation.
    – Goutam
    Sep 1 '18 at 19:23



















111














Keep in mind that HashTable was legacy class before Java Collections Framework (JCF) was introduced and was later retrofitted to implement the Map interface. So was Vector and Stack.



Therefore, always stay away from them in new code since there always better alternative in the JCF as others had pointed out.



Here is the Java collection cheat sheet that you will find useful. Notice the gray block contains the legacy class HashTable,Vector and Stack.



enter image description here






share|improve this answer































    59














    In addition to what izb said, HashMap allows null values, whereas the Hashtable does not.



    Also note that Hashtable extends the Dictionary class, which as the Javadocs state, is obsolete and has been replaced by the Map interface.






    share|improve this answer

















    • 3




      but that does not make the HashTable obsolete does it?
      – Pacerier
      Nov 1 '11 at 20:22



















    51














    Take a look at this chart. It provides comparisons between different data structures along with HashMap and Hashtable. The comparison is precise, clear and easy to understand.



    Java Collection Matrix






    share|improve this answer























    • thanks, now I know what to choose in my scenario.
      – Well Smith
      Apr 15 '18 at 3:17



















    46














    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?



    enter image description here






    share|improve this answer























    • Pretty much covered in this answer (dupicate of )- stackoverflow.com/a/39785829/432903.
      – prayagupd
      Mar 13 '17 at 2:36












    • Why do you say ~"Hashtable is a legacy class"? Where is the supporting documentation for that.
      – IgorGanapolsky
      Mar 24 '17 at 19:29






    • 2




      @IgorGanapolsky you may read this - stackoverflow.com/questions/21086307/…
      – roottraveller
      Mar 29 '17 at 9:48










    • Maintaining HashMap is costly than TreeMap. Because HashMap creates unnecessary extra buckets.
      – Abdul
      Jul 30 '18 at 2:05



















    41














    Hashtable is similar to the HashMap and has a similar interface. It is recommended that you use HashMap, unless you require support for legacy applications or you need synchronisation, as the Hashtables methods are synchronised. So in your case as you are not multi-threading, HashMaps are your best bet.






    share|improve this answer































      31














      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






      share|improve this answer





























        30














        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.



        For example, compare Java 5 Map iterating:



        for (Elem elem : map.keys()) {
        elem.doSth();
        }


        versus the old Hashtable approach:



        for (Enumeration en = htable.keys(); en.hasMoreElements(); ) {
        Elem elem = (Elem) en.nextElement();
        elem.doSth();
        }


        In Java 1.8 we are also promised to be able to construct and access HashMaps like in good old scripting languages:



        Map<String,Integer> map = { "orange" : 12, "apples" : 15 };
        map["apples"];


        Update: No, they won't land in 1.8... :(



        Are Project Coin's collection enhancements going to be in JDK8?






        share|improve this answer































          26
















          • HashTable is synchronized, if you are using it in a single thread you can use HashMap, 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.
            Youn can wrap a unsynchronized map in a synchronized one using :



            Map m = Collections.synchronizedMap(new HashMap(...));


          • HashTable can only contain non-null object as a key or as a value. HashMap can contain one null key and null values.


          • 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 ConcurrentModificationException. 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. Whereas the Enumerations returned by Hashtable's keys and elements methods are not fail-fast.


          • HashTable and HashMap are member of the Java Collections Framework (since Java 2 platform v1.2, HashTable was retrofitted to implement the Map interface).


          • HashTable is considered legacy code, the documentation advise to use ConcurrentHashMap in place of Hashtable if a thread-safe highly-concurrent implementation is desired.


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







          share|improve this answer





























            25














            HashMap and Hashtable have significant algorithmic differences as well. No one has mentioned this before so that's why I am bringing it up. HashMap 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 Hashtable 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.



            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.






            share|improve this answer































              22














              Hashtable is synchronized, whereas HashMap isn't. That makes Hashtable slower than Hashmap.



              For non-threaded apps, use HashMap since they are otherwise the same in terms of functionality.






              share|improve this answer





























                21














                Based on the info here, 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.






                share|improve this answer

















                • 5




                  It doesn't actually prevent it, it just detects it and throws an error.
                  – Bart van Heukelom
                  Dec 18 '10 at 1:44






                • 1




                  I'm pretty sure it will throw a ConncurrentModificationException before the underlying collection is modified, though I could be wrong.
                  – pkaeding
                  Jan 1 '11 at 1:46










                • It will attempt to detect concurrent modification and throw an exception. But if you're doing anything with threads, it can't make any promises. Absolutely anything can happen, including breakage.
                  – cHao
                  Apr 18 '11 at 14:03





















                18














                A Collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. A collections framework W is a unified architecture for representing and manipulating collections.



                The HashMap JDK1.2 and Hashtable JDK1.0, both are used to represent a group of objects that are represented in <Key, Value> pair. Each <Key, Value> pair is called Entry object. The collection of Entries is referred by the object of HashMap and Hashtable. 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.]





                « Superclass, Legacy and Collection Framework member



                Hashtable is a legacy class introduced in JDK1.0, which is a subclass of Dictionary class. From JDK1.2 Hashtable is re-engineered to implement the Map interface to make a member of collection framework. HashMap is a member of Java Collection Framework right from the beginning of its introduction in JDK1.2. HashMap is the subclass of the AbstractMap class.





                public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable { ... }

                public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { ... }




                « Initial capacity and Load factor



                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 "hashcollision", 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.



                HashMap constructs an empty hash table with the default initial capacity (16) and the default load factor (0.75). Where as Hashtable constructs empty hashtable with a default initial capacity (11) and load factor/fill ratio (0.75).



                Hash Map & Hashtable



                « Structural modification in case of hash collision



                HashMap, Hashtable in case of hash collisions they store the map entries in linked lists. From Java8 for HashMap if hash bucket grows beyond a certain threshold, that bucket will switch from linked list of entries to a balanced tree. 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, HashMap 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 HashMap comparable. On adding entries if bucket size reaches TREEIFY_THRESHOLD = 8 convert linked list of entries to a balanced tree, on removing entries less than TREEIFY_THRESHOLD and at most UNTREEIFY_THRESHOLD = 6 will reconvert balanced tree to linked list of entries. Java 8 SRC, stackpost



                « Collection-view iteration, Fail-Fast and Fail-Safe



                    +--------------------+-----------+-------------+
                | | Iterator | Enumeration |
                +--------------------+-----------+-------------+
                | Hashtable | fail-fast | safe |
                +--------------------+-----------+-------------+
                | HashMap | fail-fast | fail-fast |
                +--------------------+-----------+-------------+
                | ConcurrentHashMap | safe | safe |
                +--------------------+-----------+-------------+


                Iterator 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 Enumeration is fail-safe in nature. It doesn’t throw any exceptions if a collection is modified while iterating.



                According to Java API Docs, Iterator is always preferred over the Enumeration.



                NOTE: 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.



                In Java 5 introduced ConcurrentMap Interface: ConcurrentHashMap - a highly concurrent, high-performance ConcurrentMap 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 Hashtable: in addition to implementing ConcurrentMap, it supports all of the "legacy" methods peculiar to Hashtable.




                • Each HashMapEntrys value is volatile thereby ensuring fine grain consistency for contended modifications and subsequent reads; each read reflects the most recently completed update


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


                • Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.



                public static void main(String args) {

                //HashMap<String, Integer> hash = new HashMap<String, Integer>();
                Hashtable<String, Integer> hash = new Hashtable<String, Integer>();
                //ConcurrentHashMap<String, Integer> hash = new ConcurrentHashMap<>();

                new Thread() {
                @Override public void run() {
                try {
                for (int i = 10; i < 20; i++) {
                sleepThread(1);
                System.out.println("T1 :- Key"+i);
                hash.put("Key"+i, i);
                }
                System.out.println( System.identityHashCode( hash ) );
                } catch ( Exception e ) {
                e.printStackTrace();
                }
                }
                }.start();
                new Thread() {
                @Override public void run() {
                try {
                sleepThread(5);
                // ConcurrentHashMap traverse using Iterator, Enumeration is Fail-Safe.

                // Hashtable traverse using Enumeration is Fail-Safe, Iterator is Fail-Fast.
                for (Enumeration<String> e = hash.keys(); e.hasMoreElements(); ) {
                sleepThread(1);
                System.out.println("T2 : "+ e.nextElement());
                }

                // HashMap traverse using Iterator, Enumeration is Fail-Fast.
                /*
                for (Iterator< Entry<String, Integer> > it = hash.entrySet().iterator(); it.hasNext(); ) {
                sleepThread(1);
                System.out.println("T2 : "+ it.next());
                // ConcurrentModificationException at java.util.Hashtable$Enumerator.next
                }
                */

                /*
                Set< Entry<String, Integer> > entrySet = hash.entrySet();
                Iterator< Entry<String, Integer> > it = entrySet.iterator();
                Enumeration<Entry<String, Integer>> entryEnumeration = Collections.enumeration( entrySet );
                while( entryEnumeration.hasMoreElements() ) {
                sleepThread(1);
                Entry<String, Integer> nextElement = entryEnumeration.nextElement();
                System.out.println("T2 : "+ nextElement.getKey() +" : "+ nextElement.getValue() );
                //java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextNode
                // at java.util.HashMap$EntryIterator.next
                // at java.util.Collections$3.nextElement
                }
                */
                } catch ( Exception e ) {
                e.printStackTrace();
                }
                }
                }.start();

                Map<String, String> unmodifiableMap = Collections.unmodifiableMap( map );
                try {
                unmodifiableMap.put("key4", "unmodifiableMap");
                } catch (java.lang.UnsupportedOperationException e) {
                System.err.println("UnsupportedOperationException : "+ e.getMessage() );
                }
                }
                static void sleepThread( int sec ) {
                try {
                Thread.sleep( 1000 * sec );
                } catch (InterruptedException e) {
                e.printStackTrace();
                }
                }




                « Null Keys And Null Values



                HashMap allows maximum one null key and any number of null values. Where as Hashtable doesn’t allow even a single null key and null value, if the key or value null is then it throws NullPointerException. Example



                « Synchronized, Thread Safe



                Hashtable is internally synchronized. Therefore, it is very much safe to use Hashtable in multi threaded applications. Where as HashMap is not internally synchronized. Therefore, it is not safe to use HashMap in multi threaded applications without external synchronization. You can externally synchronize HashMap using Collections.synchronizedMap() method.



                « Performance



                As Hashtable is internally synchronized, this makes Hashtable slightly slower than the HashMap.





                @See




                • A red–black tree is a kind of self-balancing binary search tree

                • Performance Improvement for HashMap in Java 8






                share|improve this answer































                  15














                  For threaded apps, you can often get away with ConcurrentHashMap- depends on your performance requirements.






                  share|improve this answer





























                    14














                    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.






                    share|improve this answer





























                      13














                      1.Hashmap and HashTable both store key and value.



                      2.Hashmap can store one key as null. Hashtable can't store null.



                      3.HashMap is not synchronized but Hashtable is synchronized.



                      4.HashMap can be synchronized with Collection.SyncronizedMap(map)



                      Map hashmap = new HashMap();

                      Map map = Collections.SyncronizedMap(hashmap);





                      share|improve this answer



















                      • 1




                        the 4th diff is nice, no one mentioned it, thanks
                        – Rushabh Shah
                        Aug 10 '15 at 4:06



















                      11














                      There are 5 basic differentiations with HashTable and HashMaps.




                      1. Maps allows you to iterate and retrieve keys, values, and both key-value pairs as well, Where HashTable don't have all this capability.

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

                      3. In hashmap you can remove element while iterating, safely. where as it is not possible in hashtables.

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

                      5. HashTable won't allow null keys or null values. Where as HashMap allows one null key, and multiple null values.






                      share|improve this answer































                        11














                        My small contribution :





                        1. First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe while Hashtable is a thread-safe collection.


                        2. Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable.


                        3. Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.








                        share|improve this answer































                          8














                          HashTable is a legacy class in the jdk that shouldn't be used anymore. Replace usages of it with ConcurrentHashMap. If you don't require thread safety, use HashMap which isn't threadsafe but faster and uses less memory.






                          share|improve this answer























                          • Why are you repeating an already given answer?
                            – BalusC
                            Aug 6 '15 at 8:06










                          • Because I thought the other answers, at the time, didn't dismiss HashTable but explained that it was threadsafe. The truth is that as soon as you see HashTable in code, you should replace it with ConcurrentHashMap without skipping a beat. And if thread safety is not a concern then HashMap can be used to improve performance a bit.
                            – jontejj
                            Aug 7 '15 at 8:29



















                          7














                          1)Hashtable is synchronized whereas hashmap is not.
                          2)Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.



                          3)HashMap permits null values in it, while Hashtable doesn't.






                          share|improve this answer

















                          • 3




                            HashMap iterator is fail-fast not fail-safe. Thats why we have ConcurrentHashMap that allows modification while iteration. Check this post journaldev.com/122/…
                            – Pankaj
                            Jan 28 '13 at 21:13






                          • 3




                            Why are you repeating an already given answer?
                            – BalusC
                            Aug 6 '15 at 8:02



















                          6














                          Hashtable:



                          Hashtable 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 NullPointerException if you add null value. It is synchronized. So it comes with its cost. Only one thread can access HashTable at a particular time.



                          Example :



                          import java.util.Map;
                          import java.util.Hashtable;

                          public class TestClass {

                          public static void main(String args[ ]) {
                          Map<Integer,String> states= new Hashtable<Integer,String>();
                          states.put(1, "INDIA");
                          states.put(2, "USA");

                          states.put(3, null); //will throw NullPointerEcxeption at runtime

                          System.out.println(states.get(1));
                          System.out.println(states.get(2));
                          // System.out.println(states.get(3));

                          }
                          }


                          HashMap:



                          HashMap is like Hashtable but it also accepts key value pair. It allows null for both the keys and the values. Its performance better is better than HashTable, because it is unsynchronized.



                          Example:



                          import java.util.HashMap;
                          import java.util.Map;

                          public class TestClass {

                          public static void main(String args[ ]) {
                          Map<Integer,String> states = new HashMap<Integer,String>();
                          states.put(1, "INDIA");
                          states.put(2, "USA");

                          states.put(3, null); // Okay
                          states.put(null,"UK");

                          System.out.println(states.get(1));
                          System.out.println(states.get(2));
                          System.out.println(states.get(3));

                          }
                          }





                          share|improve this answer































                            6














                            HashMap and HashTable




                            • Some important points about HashMap and HashTable.
                              please read below details.


                            1) Hashtable and Hashmap implement the java.util.Map interface
                            2) Both Hashmap and Hashtable is the hash based collection. and working on hashing.
                            so these are similarity of HashMap and HashTable.




                            • What is the difference between HashMap and HashTable?


                            1) First difference is HashMap is not thread safe While HashTable is ThreadSafe

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






                            share|improve this answer



















                            • 1




                              Down-voted because this answer is not correct in some aspects. Hashtable does not implement the Map interface, but only extends the Dictionary class, which is obsolete.
                              – Yannis Sermetziadis
                              Oct 25 '17 at 5:42



















                            6














                            HashMap: It is a class available inside java.util package and it is used to store the element in key and value format.



                            Hashtable: It is a legacy class which is being recognized inside collection framework.






                            share|improve this answer



















                            • 4




                              Why are you repeating an already given answer?
                              – BalusC
                              Aug 6 '15 at 8:02



















                            4














                            HashMaps gives you freedom of synchronization and debugging is lot more easier






                            share|improve this answer

















                            • 2




                              Why are you repeating an already given answer?
                              – BalusC
                              Aug 6 '15 at 8:03






                            • 2




                              What does ~"freedom of synchronization" mean?
                              – IgorGanapolsky
                              Mar 24 '17 at 19:03



















                            4














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






                            share|improve this answer





















                            • Is that a comprehensive description of differences between the two apis?
                              – IgorGanapolsky
                              Mar 24 '17 at 19:04










                            • Yes (sic!). That's all GWT developers need to know about it.
                              – pong
                              Mar 24 '17 at 19:41



















                            4














                            Synchronization or Thread Safe :



                            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.



                            Null keys and null values :



                            HashMap allows one null key and any number of null values.Hashtable does not allow null keys or values.



                            Iterating the values:



                            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.



                            Superclass and Legacy :



                            HashMap is subclass of AbstractMap class whereas Hashtable is subclass of Dictionary class.



                            Performance :



                            As HashMap is not synchronized it is faster as compared to Hashtable.



                            Refer http://modernpathshala.com/Article/1020/difference-between-hashmap-and-hashtable-in-java for examples and interview questions and quiz related to Java collection






                            share|improve this answer



























                              1 2
                              next


                              protected by Community Mar 16 '12 at 19:13



                              Thank you for your interest in this question.
                              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                              Would you like to answer one of these unanswered questions instead?














                              34 Answers
                              34






                              active

                              oldest

                              votes








                              34 Answers
                              34






                              active

                              oldest

                              votes









                              active

                              oldest

                              votes






                              active

                              oldest

                              votes








                              1 2
                              next










                              3362














                              There are several differences between HashMap and Hashtable in Java:




                              1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.


                              2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.


                              3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.



                              Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.






                              share|improve this answer



















                              • 52




                                If you want to make a HashMap thread-safe, use Collections.synchronizedMap().
                                – Rok Strniša
                                Nov 22 '11 at 18:48






                              • 213




                                I would also comment that the naive approach to thread-safety in Hashtable ("synchronizing every method should take care of any concurrency problems!") makes it very much worse for threaded applications. You're better off externally synchronizing a HashMap (and thinking about the consequences), or using a ConcurrentMap implementation (and exploiting its extended API for concurrency). Bottom line: the only reason to use Hashtable is when a legacy API (from ca. 1996) requires it.
                                – erickson
                                Mar 16 '12 at 17:19






                              • 6




                                HashMap gives flexibility to programmer to write threadSafe code when they actually use it. It happened rarely that I needed a thread safe collection like ConcurrentHashMap or HashTable. What I needed is certain set of functions or certain statements in a synchronized block to be threadsafe.
                                – Gaurava Agarwal
                                Jun 27 '16 at 9:00












                              • Hashtable is obsolete and we are using HashMap for non thread safe environment. If you need thread safety then you can use Collections.synchronizedMap() or use ConcurrentHashMap which is more efficient that hashtable.
                                – Maneesh Kumar
                                Mar 30 '18 at 3:45










                              • It's obsolete but not deprecated and I'm wondering why this is. I'm guessing removing this class (and Vector for the same reasons) would break too much existing code and annotating with @Deprecated would imply an intention to remove the code, which apparently is not there.
                                – Jilles van Gurp
                                May 19 '18 at 8:11
















                              3362














                              There are several differences between HashMap and Hashtable in Java:




                              1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.


                              2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.


                              3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.



                              Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.






                              share|improve this answer



















                              • 52




                                If you want to make a HashMap thread-safe, use Collections.synchronizedMap().
                                – Rok Strniša
                                Nov 22 '11 at 18:48






                              • 213




                                I would also comment that the naive approach to thread-safety in Hashtable ("synchronizing every method should take care of any concurrency problems!") makes it very much worse for threaded applications. You're better off externally synchronizing a HashMap (and thinking about the consequences), or using a ConcurrentMap implementation (and exploiting its extended API for concurrency). Bottom line: the only reason to use Hashtable is when a legacy API (from ca. 1996) requires it.
                                – erickson
                                Mar 16 '12 at 17:19






                              • 6




                                HashMap gives flexibility to programmer to write threadSafe code when they actually use it. It happened rarely that I needed a thread safe collection like ConcurrentHashMap or HashTable. What I needed is certain set of functions or certain statements in a synchronized block to be threadsafe.
                                – Gaurava Agarwal
                                Jun 27 '16 at 9:00












                              • Hashtable is obsolete and we are using HashMap for non thread safe environment. If you need thread safety then you can use Collections.synchronizedMap() or use ConcurrentHashMap which is more efficient that hashtable.
                                – Maneesh Kumar
                                Mar 30 '18 at 3:45










                              • It's obsolete but not deprecated and I'm wondering why this is. I'm guessing removing this class (and Vector for the same reasons) would break too much existing code and annotating with @Deprecated would imply an intention to remove the code, which apparently is not there.
                                – Jilles van Gurp
                                May 19 '18 at 8:11














                              3362












                              3362








                              3362






                              There are several differences between HashMap and Hashtable in Java:




                              1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.


                              2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.


                              3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.



                              Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.






                              share|improve this answer














                              There are several differences between HashMap and Hashtable in Java:




                              1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.


                              2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.


                              3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.



                              Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Sep 13 '18 at 19:38

























                              answered Sep 2 '08 at 23:02









                              Josh Brown

                              39.3k84576




                              39.3k84576








                              • 52




                                If you want to make a HashMap thread-safe, use Collections.synchronizedMap().
                                – Rok Strniša
                                Nov 22 '11 at 18:48






                              • 213




                                I would also comment that the naive approach to thread-safety in Hashtable ("synchronizing every method should take care of any concurrency problems!") makes it very much worse for threaded applications. You're better off externally synchronizing a HashMap (and thinking about the consequences), or using a ConcurrentMap implementation (and exploiting its extended API for concurrency). Bottom line: the only reason to use Hashtable is when a legacy API (from ca. 1996) requires it.
                                – erickson
                                Mar 16 '12 at 17:19






                              • 6




                                HashMap gives flexibility to programmer to write threadSafe code when they actually use it. It happened rarely that I needed a thread safe collection like ConcurrentHashMap or HashTable. What I needed is certain set of functions or certain statements in a synchronized block to be threadsafe.
                                – Gaurava Agarwal
                                Jun 27 '16 at 9:00












                              • Hashtable is obsolete and we are using HashMap for non thread safe environment. If you need thread safety then you can use Collections.synchronizedMap() or use ConcurrentHashMap which is more efficient that hashtable.
                                – Maneesh Kumar
                                Mar 30 '18 at 3:45










                              • It's obsolete but not deprecated and I'm wondering why this is. I'm guessing removing this class (and Vector for the same reasons) would break too much existing code and annotating with @Deprecated would imply an intention to remove the code, which apparently is not there.
                                – Jilles van Gurp
                                May 19 '18 at 8:11














                              • 52




                                If you want to make a HashMap thread-safe, use Collections.synchronizedMap().
                                – Rok Strniša
                                Nov 22 '11 at 18:48






                              • 213




                                I would also comment that the naive approach to thread-safety in Hashtable ("synchronizing every method should take care of any concurrency problems!") makes it very much worse for threaded applications. You're better off externally synchronizing a HashMap (and thinking about the consequences), or using a ConcurrentMap implementation (and exploiting its extended API for concurrency). Bottom line: the only reason to use Hashtable is when a legacy API (from ca. 1996) requires it.
                                – erickson
                                Mar 16 '12 at 17:19






                              • 6




                                HashMap gives flexibility to programmer to write threadSafe code when they actually use it. It happened rarely that I needed a thread safe collection like ConcurrentHashMap or HashTable. What I needed is certain set of functions or certain statements in a synchronized block to be threadsafe.
                                – Gaurava Agarwal
                                Jun 27 '16 at 9:00












                              • Hashtable is obsolete and we are using HashMap for non thread safe environment. If you need thread safety then you can use Collections.synchronizedMap() or use ConcurrentHashMap which is more efficient that hashtable.
                                – Maneesh Kumar
                                Mar 30 '18 at 3:45










                              • It's obsolete but not deprecated and I'm wondering why this is. I'm guessing removing this class (and Vector for the same reasons) would break too much existing code and annotating with @Deprecated would imply an intention to remove the code, which apparently is not there.
                                – Jilles van Gurp
                                May 19 '18 at 8:11








                              52




                              52




                              If you want to make a HashMap thread-safe, use Collections.synchronizedMap().
                              – Rok Strniša
                              Nov 22 '11 at 18:48




                              If you want to make a HashMap thread-safe, use Collections.synchronizedMap().
                              – Rok Strniša
                              Nov 22 '11 at 18:48




                              213




                              213




                              I would also comment that the naive approach to thread-safety in Hashtable ("synchronizing every method should take care of any concurrency problems!") makes it very much worse for threaded applications. You're better off externally synchronizing a HashMap (and thinking about the consequences), or using a ConcurrentMap implementation (and exploiting its extended API for concurrency). Bottom line: the only reason to use Hashtable is when a legacy API (from ca. 1996) requires it.
                              – erickson
                              Mar 16 '12 at 17:19




                              I would also comment that the naive approach to thread-safety in Hashtable ("synchronizing every method should take care of any concurrency problems!") makes it very much worse for threaded applications. You're better off externally synchronizing a HashMap (and thinking about the consequences), or using a ConcurrentMap implementation (and exploiting its extended API for concurrency). Bottom line: the only reason to use Hashtable is when a legacy API (from ca. 1996) requires it.
                              – erickson
                              Mar 16 '12 at 17:19




                              6




                              6




                              HashMap gives flexibility to programmer to write threadSafe code when they actually use it. It happened rarely that I needed a thread safe collection like ConcurrentHashMap or HashTable. What I needed is certain set of functions or certain statements in a synchronized block to be threadsafe.
                              – Gaurava Agarwal
                              Jun 27 '16 at 9:00






                              HashMap gives flexibility to programmer to write threadSafe code when they actually use it. It happened rarely that I needed a thread safe collection like ConcurrentHashMap or HashTable. What I needed is certain set of functions or certain statements in a synchronized block to be threadsafe.
                              – Gaurava Agarwal
                              Jun 27 '16 at 9:00














                              Hashtable is obsolete and we are using HashMap for non thread safe environment. If you need thread safety then you can use Collections.synchronizedMap() or use ConcurrentHashMap which is more efficient that hashtable.
                              – Maneesh Kumar
                              Mar 30 '18 at 3:45




                              Hashtable is obsolete and we are using HashMap for non thread safe environment. If you need thread safety then you can use Collections.synchronizedMap() or use ConcurrentHashMap which is more efficient that hashtable.
                              – Maneesh Kumar
                              Mar 30 '18 at 3:45












                              It's obsolete but not deprecated and I'm wondering why this is. I'm guessing removing this class (and Vector for the same reasons) would break too much existing code and annotating with @Deprecated would imply an intention to remove the code, which apparently is not there.
                              – Jilles van Gurp
                              May 19 '18 at 8:11




                              It's obsolete but not deprecated and I'm wondering why this is. I'm guessing removing this class (and Vector for the same reasons) would break too much existing code and annotating with @Deprecated would imply an intention to remove the code, which apparently is not there.
                              – Jilles van Gurp
                              May 19 '18 at 8:11













                              610














                              Note, that a lot of the answers state that Hashtable is synchronised. In practice this buys you very little. 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 synchronisation.



                              A very common idiom is to "check then put" - i.e. look for an entry in the Map, and add it if it does not already exist. This is not in any way an atomic operation whether you use Hashtable or HashMap.



                              An equivalently synchronised HashMap can be obtained by:



                              Collections.synchronizedMap(myMap);


                              But to correctly implement this logic you need additional synchronisation of the form:



                              synchronized(myMap) {
                              if (!myMap.containsKey("tomato"))
                              myMap.put("tomato", "red");
                              }


                              Even iterating over a Hashtable's entries (or a HashMap obtained by Collections.synchronizedMap) is not thread safe unless you also guard the Map from being modified through additional synchronization.



                              Implementations of the ConcurrentMap interface (for example ConcurrentHashMap) solve some of this by including thread safe check-then-act semantics such as:



                              ConcurrentMap.putIfAbsent(key, value);





                              share|improve this answer



















                              • 46




                                Also note that if a HashMap is modified, iterators pointing to it are rendered invalid.
                                – Chris K
                                Apr 22 '09 at 22:03






                              • 18




                                Iterator will throw ConcurrentModificationException, right?
                                – Bhushan
                                Jun 30 '11 at 2:26






                              • 3




                                So is there any difference between synchronized(myMap) {...} and ConcurrentHashMap in terms of thread safe?
                                – telebog
                                Nov 11 '11 at 16:48








                              • 3




                                Very true, I tried to explain same here..lovehasija.com/2012/08/16/…
                                – Love Hasija
                                Sep 20 '12 at 10:21












                              • @Bhushan: It will throw on a best-effort basis, this is not guaranteed behavior: docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
                                – Matt Stephenson
                                Oct 3 '13 at 18:49
















                              610














                              Note, that a lot of the answers state that Hashtable is synchronised. In practice this buys you very little. 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 synchronisation.



                              A very common idiom is to "check then put" - i.e. look for an entry in the Map, and add it if it does not already exist. This is not in any way an atomic operation whether you use Hashtable or HashMap.



                              An equivalently synchronised HashMap can be obtained by:



                              Collections.synchronizedMap(myMap);


                              But to correctly implement this logic you need additional synchronisation of the form:



                              synchronized(myMap) {
                              if (!myMap.containsKey("tomato"))
                              myMap.put("tomato", "red");
                              }


                              Even iterating over a Hashtable's entries (or a HashMap obtained by Collections.synchronizedMap) is not thread safe unless you also guard the Map from being modified through additional synchronization.



                              Implementations of the ConcurrentMap interface (for example ConcurrentHashMap) solve some of this by including thread safe check-then-act semantics such as:



                              ConcurrentMap.putIfAbsent(key, value);





                              share|improve this answer



















                              • 46




                                Also note that if a HashMap is modified, iterators pointing to it are rendered invalid.
                                – Chris K
                                Apr 22 '09 at 22:03






                              • 18




                                Iterator will throw ConcurrentModificationException, right?
                                – Bhushan
                                Jun 30 '11 at 2:26






                              • 3




                                So is there any difference between synchronized(myMap) {...} and ConcurrentHashMap in terms of thread safe?
                                – telebog
                                Nov 11 '11 at 16:48








                              • 3




                                Very true, I tried to explain same here..lovehasija.com/2012/08/16/…
                                – Love Hasija
                                Sep 20 '12 at 10:21












                              • @Bhushan: It will throw on a best-effort basis, this is not guaranteed behavior: docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
                                – Matt Stephenson
                                Oct 3 '13 at 18:49














                              610












                              610








                              610






                              Note, that a lot of the answers state that Hashtable is synchronised. In practice this buys you very little. 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 synchronisation.



                              A very common idiom is to "check then put" - i.e. look for an entry in the Map, and add it if it does not already exist. This is not in any way an atomic operation whether you use Hashtable or HashMap.



                              An equivalently synchronised HashMap can be obtained by:



                              Collections.synchronizedMap(myMap);


                              But to correctly implement this logic you need additional synchronisation of the form:



                              synchronized(myMap) {
                              if (!myMap.containsKey("tomato"))
                              myMap.put("tomato", "red");
                              }


                              Even iterating over a Hashtable's entries (or a HashMap obtained by Collections.synchronizedMap) is not thread safe unless you also guard the Map from being modified through additional synchronization.



                              Implementations of the ConcurrentMap interface (for example ConcurrentHashMap) solve some of this by including thread safe check-then-act semantics such as:



                              ConcurrentMap.putIfAbsent(key, value);





                              share|improve this answer














                              Note, that a lot of the answers state that Hashtable is synchronised. In practice this buys you very little. 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 synchronisation.



                              A very common idiom is to "check then put" - i.e. look for an entry in the Map, and add it if it does not already exist. This is not in any way an atomic operation whether you use Hashtable or HashMap.



                              An equivalently synchronised HashMap can be obtained by:



                              Collections.synchronizedMap(myMap);


                              But to correctly implement this logic you need additional synchronisation of the form:



                              synchronized(myMap) {
                              if (!myMap.containsKey("tomato"))
                              myMap.put("tomato", "red");
                              }


                              Even iterating over a Hashtable's entries (or a HashMap obtained by Collections.synchronizedMap) is not thread safe unless you also guard the Map from being modified through additional synchronization.



                              Implementations of the ConcurrentMap interface (for example ConcurrentHashMap) solve some of this by including thread safe check-then-act semantics such as:



                              ConcurrentMap.putIfAbsent(key, value);






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Dec 5 '14 at 14:45









                              Mickey Tin

                              1,51753150




                              1,51753150










                              answered Sep 3 '08 at 11:00









                              serg10

                              21.3k135987




                              21.3k135987








                              • 46




                                Also note that if a HashMap is modified, iterators pointing to it are rendered invalid.
                                – Chris K
                                Apr 22 '09 at 22:03






                              • 18




                                Iterator will throw ConcurrentModificationException, right?
                                – Bhushan
                                Jun 30 '11 at 2:26






                              • 3




                                So is there any difference between synchronized(myMap) {...} and ConcurrentHashMap in terms of thread safe?
                                – telebog
                                Nov 11 '11 at 16:48








                              • 3




                                Very true, I tried to explain same here..lovehasija.com/2012/08/16/…
                                – Love Hasija
                                Sep 20 '12 at 10:21












                              • @Bhushan: It will throw on a best-effort basis, this is not guaranteed behavior: docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
                                – Matt Stephenson
                                Oct 3 '13 at 18:49














                              • 46




                                Also note that if a HashMap is modified, iterators pointing to it are rendered invalid.
                                – Chris K
                                Apr 22 '09 at 22:03






                              • 18




                                Iterator will throw ConcurrentModificationException, right?
                                – Bhushan
                                Jun 30 '11 at 2:26






                              • 3




                                So is there any difference between synchronized(myMap) {...} and ConcurrentHashMap in terms of thread safe?
                                – telebog
                                Nov 11 '11 at 16:48








                              • 3




                                Very true, I tried to explain same here..lovehasija.com/2012/08/16/…
                                – Love Hasija
                                Sep 20 '12 at 10:21












                              • @Bhushan: It will throw on a best-effort basis, this is not guaranteed behavior: docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
                                – Matt Stephenson
                                Oct 3 '13 at 18:49








                              46




                              46




                              Also note that if a HashMap is modified, iterators pointing to it are rendered invalid.
                              – Chris K
                              Apr 22 '09 at 22:03




                              Also note that if a HashMap is modified, iterators pointing to it are rendered invalid.
                              – Chris K
                              Apr 22 '09 at 22:03




                              18




                              18




                              Iterator will throw ConcurrentModificationException, right?
                              – Bhushan
                              Jun 30 '11 at 2:26




                              Iterator will throw ConcurrentModificationException, right?
                              – Bhushan
                              Jun 30 '11 at 2:26




                              3




                              3




                              So is there any difference between synchronized(myMap) {...} and ConcurrentHashMap in terms of thread safe?
                              – telebog
                              Nov 11 '11 at 16:48






                              So is there any difference between synchronized(myMap) {...} and ConcurrentHashMap in terms of thread safe?
                              – telebog
                              Nov 11 '11 at 16:48






                              3




                              3




                              Very true, I tried to explain same here..lovehasija.com/2012/08/16/…
                              – Love Hasija
                              Sep 20 '12 at 10:21






                              Very true, I tried to explain same here..lovehasija.com/2012/08/16/…
                              – Love Hasija
                              Sep 20 '12 at 10:21














                              @Bhushan: It will throw on a best-effort basis, this is not guaranteed behavior: docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
                              – Matt Stephenson
                              Oct 3 '13 at 18:49




                              @Bhushan: It will throw on a best-effort basis, this is not guaranteed behavior: docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
                              – Matt Stephenson
                              Oct 3 '13 at 18:49











                              310














                              Hashtable is considered legacy code. There's nothing about Hashtable that can't be done using HashMap or derivations of HashMap, so for new code, I don't see any justification for going back to Hashtable.






                              share|improve this answer



















                              • 92




                                From Hashtable javadoc (emphasis added): "As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework." However, you are right that it is legacy code. All the benefits of synchronization can be obtained more efficiently with Collections.synchronizedMap(HashMap). (Similar to Vector being a legacy version of Collections.synchronizedList(ArrayList).)
                                – Kip
                                Jan 19 '10 at 22:09






                              • 15




                                @aberrant80: unfortunately you have no choice between the two and have to use Hashtable when programming for J2ME...
                                – pwes
                                Jan 12 '12 at 8:13






                              • 5




                                this answer should be deleted. it contains incorrect information and has a lot of upvotes.
                                – anon58192932
                                Jan 22 '16 at 20:40










                              • @anon58192932 Is it possible to edit the question to fix it?
                                – GC_
                                Oct 14 '16 at 15:39








                              • 1




                                We have to get the attention of the poster @aberrant80 or an admin by flagging. Flagging could help - will try that now.
                                – anon58192932
                                Oct 14 '16 at 20:05
















                              310














                              Hashtable is considered legacy code. There's nothing about Hashtable that can't be done using HashMap or derivations of HashMap, so for new code, I don't see any justification for going back to Hashtable.






                              share|improve this answer



















                              • 92




                                From Hashtable javadoc (emphasis added): "As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework." However, you are right that it is legacy code. All the benefits of synchronization can be obtained more efficiently with Collections.synchronizedMap(HashMap). (Similar to Vector being a legacy version of Collections.synchronizedList(ArrayList).)
                                – Kip
                                Jan 19 '10 at 22:09






                              • 15




                                @aberrant80: unfortunately you have no choice between the two and have to use Hashtable when programming for J2ME...
                                – pwes
                                Jan 12 '12 at 8:13






                              • 5




                                this answer should be deleted. it contains incorrect information and has a lot of upvotes.
                                – anon58192932
                                Jan 22 '16 at 20:40










                              • @anon58192932 Is it possible to edit the question to fix it?
                                – GC_
                                Oct 14 '16 at 15:39








                              • 1




                                We have to get the attention of the poster @aberrant80 or an admin by flagging. Flagging could help - will try that now.
                                – anon58192932
                                Oct 14 '16 at 20:05














                              310












                              310








                              310






                              Hashtable is considered legacy code. There's nothing about Hashtable that can't be done using HashMap or derivations of HashMap, so for new code, I don't see any justification for going back to Hashtable.






                              share|improve this answer














                              Hashtable is considered legacy code. There's nothing about Hashtable that can't be done using HashMap or derivations of HashMap, so for new code, I don't see any justification for going back to Hashtable.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Aug 7 '18 at 12:18









                              kryger

                              9,14553654




                              9,14553654










                              answered Jun 25 '09 at 1:46









                              aberrant80

                              8,27953558




                              8,27953558








                              • 92




                                From Hashtable javadoc (emphasis added): "As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework." However, you are right that it is legacy code. All the benefits of synchronization can be obtained more efficiently with Collections.synchronizedMap(HashMap). (Similar to Vector being a legacy version of Collections.synchronizedList(ArrayList).)
                                – Kip
                                Jan 19 '10 at 22:09






                              • 15




                                @aberrant80: unfortunately you have no choice between the two and have to use Hashtable when programming for J2ME...
                                – pwes
                                Jan 12 '12 at 8:13






                              • 5




                                this answer should be deleted. it contains incorrect information and has a lot of upvotes.
                                – anon58192932
                                Jan 22 '16 at 20:40










                              • @anon58192932 Is it possible to edit the question to fix it?
                                – GC_
                                Oct 14 '16 at 15:39








                              • 1




                                We have to get the attention of the poster @aberrant80 or an admin by flagging. Flagging could help - will try that now.
                                – anon58192932
                                Oct 14 '16 at 20:05














                              • 92




                                From Hashtable javadoc (emphasis added): "As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework." However, you are right that it is legacy code. All the benefits of synchronization can be obtained more efficiently with Collections.synchronizedMap(HashMap). (Similar to Vector being a legacy version of Collections.synchronizedList(ArrayList).)
                                – Kip
                                Jan 19 '10 at 22:09






                              • 15




                                @aberrant80: unfortunately you have no choice between the two and have to use Hashtable when programming for J2ME...
                                – pwes
                                Jan 12 '12 at 8:13






                              • 5




                                this answer should be deleted. it contains incorrect information and has a lot of upvotes.
                                – anon58192932
                                Jan 22 '16 at 20:40










                              • @anon58192932 Is it possible to edit the question to fix it?
                                – GC_
                                Oct 14 '16 at 15:39








                              • 1




                                We have to get the attention of the poster @aberrant80 or an admin by flagging. Flagging could help - will try that now.
                                – anon58192932
                                Oct 14 '16 at 20:05








                              92




                              92




                              From Hashtable javadoc (emphasis added): "As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework." However, you are right that it is legacy code. All the benefits of synchronization can be obtained more efficiently with Collections.synchronizedMap(HashMap). (Similar to Vector being a legacy version of Collections.synchronizedList(ArrayList).)
                              – Kip
                              Jan 19 '10 at 22:09




                              From Hashtable javadoc (emphasis added): "As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework." However, you are right that it is legacy code. All the benefits of synchronization can be obtained more efficiently with Collections.synchronizedMap(HashMap). (Similar to Vector being a legacy version of Collections.synchronizedList(ArrayList).)
                              – Kip
                              Jan 19 '10 at 22:09




                              15




                              15




                              @aberrant80: unfortunately you have no choice between the two and have to use Hashtable when programming for J2ME...
                              – pwes
                              Jan 12 '12 at 8:13




                              @aberrant80: unfortunately you have no choice between the two and have to use Hashtable when programming for J2ME...
                              – pwes
                              Jan 12 '12 at 8:13




                              5




                              5




                              this answer should be deleted. it contains incorrect information and has a lot of upvotes.
                              – anon58192932
                              Jan 22 '16 at 20:40




                              this answer should be deleted. it contains incorrect information and has a lot of upvotes.
                              – anon58192932
                              Jan 22 '16 at 20:40












                              @anon58192932 Is it possible to edit the question to fix it?
                              – GC_
                              Oct 14 '16 at 15:39






                              @anon58192932 Is it possible to edit the question to fix it?
                              – GC_
                              Oct 14 '16 at 15:39






                              1




                              1




                              We have to get the attention of the poster @aberrant80 or an admin by flagging. Flagging could help - will try that now.
                              – anon58192932
                              Oct 14 '16 at 20:05




                              We have to get the attention of the poster @aberrant80 or an admin by flagging. Flagging could help - will try that now.
                              – anon58192932
                              Oct 14 '16 at 20:05











                              157














                              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 from 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







                              share|improve this answer



















                              • 18




                                This answer contains at least 2 significant factual inaccuracies. It certainly DOES NOT deserve this many upvotes.
                                – Stephen C
                                Sep 9 '13 at 8:05






                              • 55




                                1) HashMap's iterators are NOT fail-safe. They are fail-fast. There is a huge difference in meaning between those two terms. 2) There is no set operation on a HashMap. 3) The put(...) operation won't throw IllegalArgumentException if there was a previous change. 4) The fail-fast behaviour of HashMap also occurs if you change a mapping. 5) The fail-fast behaviour is guaranteed. (What is not guaranteed is the behaviour of a HashTable if you make a concurrent modification. The actual behaviour is ... unpredictable.)
                                – Stephen C
                                Sep 9 '13 at 8:14






                              • 24




                                6) Hashtable does not guarantee that the order of map elements will be stable over time either. (You are perhaps confusing Hashtable with LinkedHashMap.)
                                – Stephen C
                                Sep 9 '13 at 8:16






                              • 3




                                Anyone else really worried that students these days are getting the errant idea that getting "synchronized versions" of the collections somehow means that you don't have to externally synchronize compound operations? My favorite example of this being thing.set(thing.get() + 1); which more often than not catches newbies by surprise as completely unprotected, especially if the get() and set() are synchronized methods. Many of them are expecting magic.
                                – user4229245
                                May 4 '15 at 22:26












                              • Iterators on HashMap is not fail-safe
                                – Abdul
                                Jul 30 '18 at 1:56
















                              157














                              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 from 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







                              share|improve this answer



















                              • 18




                                This answer contains at least 2 significant factual inaccuracies. It certainly DOES NOT deserve this many upvotes.
                                – Stephen C
                                Sep 9 '13 at 8:05






                              • 55




                                1) HashMap's iterators are NOT fail-safe. They are fail-fast. There is a huge difference in meaning between those two terms. 2) There is no set operation on a HashMap. 3) The put(...) operation won't throw IllegalArgumentException if there was a previous change. 4) The fail-fast behaviour of HashMap also occurs if you change a mapping. 5) The fail-fast behaviour is guaranteed. (What is not guaranteed is the behaviour of a HashTable if you make a concurrent modification. The actual behaviour is ... unpredictable.)
                                – Stephen C
                                Sep 9 '13 at 8:14






                              • 24




                                6) Hashtable does not guarantee that the order of map elements will be stable over time either. (You are perhaps confusing Hashtable with LinkedHashMap.)
                                – Stephen C
                                Sep 9 '13 at 8:16






                              • 3




                                Anyone else really worried that students these days are getting the errant idea that getting "synchronized versions" of the collections somehow means that you don't have to externally synchronize compound operations? My favorite example of this being thing.set(thing.get() + 1); which more often than not catches newbies by surprise as completely unprotected, especially if the get() and set() are synchronized methods. Many of them are expecting magic.
                                – user4229245
                                May 4 '15 at 22:26












                              • Iterators on HashMap is not fail-safe
                                – Abdul
                                Jul 30 '18 at 1:56














                              157












                              157








                              157






                              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 from 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







                              share|improve this answer














                              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 from 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








                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jul 7 '14 at 8:32









                              Wilfred Hughes

                              16.6k1091129




                              16.6k1091129










                              answered Oct 4 '11 at 6:39









                              sravan

                              4,28712533




                              4,28712533








                              • 18




                                This answer contains at least 2 significant factual inaccuracies. It certainly DOES NOT deserve this many upvotes.
                                – Stephen C
                                Sep 9 '13 at 8:05






                              • 55




                                1) HashMap's iterators are NOT fail-safe. They are fail-fast. There is a huge difference in meaning between those two terms. 2) There is no set operation on a HashMap. 3) The put(...) operation won't throw IllegalArgumentException if there was a previous change. 4) The fail-fast behaviour of HashMap also occurs if you change a mapping. 5) The fail-fast behaviour is guaranteed. (What is not guaranteed is the behaviour of a HashTable if you make a concurrent modification. The actual behaviour is ... unpredictable.)
                                – Stephen C
                                Sep 9 '13 at 8:14






                              • 24




                                6) Hashtable does not guarantee that the order of map elements will be stable over time either. (You are perhaps confusing Hashtable with LinkedHashMap.)
                                – Stephen C
                                Sep 9 '13 at 8:16






                              • 3




                                Anyone else really worried that students these days are getting the errant idea that getting "synchronized versions" of the collections somehow means that you don't have to externally synchronize compound operations? My favorite example of this being thing.set(thing.get() + 1); which more often than not catches newbies by surprise as completely unprotected, especially if the get() and set() are synchronized methods. Many of them are expecting magic.
                                – user4229245
                                May 4 '15 at 22:26












                              • Iterators on HashMap is not fail-safe
                                – Abdul
                                Jul 30 '18 at 1:56














                              • 18




                                This answer contains at least 2 significant factual inaccuracies. It certainly DOES NOT deserve this many upvotes.
                                – Stephen C
                                Sep 9 '13 at 8:05






                              • 55




                                1) HashMap's iterators are NOT fail-safe. They are fail-fast. There is a huge difference in meaning between those two terms. 2) There is no set operation on a HashMap. 3) The put(...) operation won't throw IllegalArgumentException if there was a previous change. 4) The fail-fast behaviour of HashMap also occurs if you change a mapping. 5) The fail-fast behaviour is guaranteed. (What is not guaranteed is the behaviour of a HashTable if you make a concurrent modification. The actual behaviour is ... unpredictable.)
                                – Stephen C
                                Sep 9 '13 at 8:14






                              • 24




                                6) Hashtable does not guarantee that the order of map elements will be stable over time either. (You are perhaps confusing Hashtable with LinkedHashMap.)
                                – Stephen C
                                Sep 9 '13 at 8:16






                              • 3




                                Anyone else really worried that students these days are getting the errant idea that getting "synchronized versions" of the collections somehow means that you don't have to externally synchronize compound operations? My favorite example of this being thing.set(thing.get() + 1); which more often than not catches newbies by surprise as completely unprotected, especially if the get() and set() are synchronized methods. Many of them are expecting magic.
                                – user4229245
                                May 4 '15 at 22:26












                              • Iterators on HashMap is not fail-safe
                                – Abdul
                                Jul 30 '18 at 1:56








                              18




                              18




                              This answer contains at least 2 significant factual inaccuracies. It certainly DOES NOT deserve this many upvotes.
                              – Stephen C
                              Sep 9 '13 at 8:05




                              This answer contains at least 2 significant factual inaccuracies. It certainly DOES NOT deserve this many upvotes.
                              – Stephen C
                              Sep 9 '13 at 8:05




                              55




                              55




                              1) HashMap's iterators are NOT fail-safe. They are fail-fast. There is a huge difference in meaning between those two terms. 2) There is no set operation on a HashMap. 3) The put(...) operation won't throw IllegalArgumentException if there was a previous change. 4) The fail-fast behaviour of HashMap also occurs if you change a mapping. 5) The fail-fast behaviour is guaranteed. (What is not guaranteed is the behaviour of a HashTable if you make a concurrent modification. The actual behaviour is ... unpredictable.)
                              – Stephen C
                              Sep 9 '13 at 8:14




                              1) HashMap's iterators are NOT fail-safe. They are fail-fast. There is a huge difference in meaning between those two terms. 2) There is no set operation on a HashMap. 3) The put(...) operation won't throw IllegalArgumentException if there was a previous change. 4) The fail-fast behaviour of HashMap also occurs if you change a mapping. 5) The fail-fast behaviour is guaranteed. (What is not guaranteed is the behaviour of a HashTable if you make a concurrent modification. The actual behaviour is ... unpredictable.)
                              – Stephen C
                              Sep 9 '13 at 8:14




                              24




                              24




                              6) Hashtable does not guarantee that the order of map elements will be stable over time either. (You are perhaps confusing Hashtable with LinkedHashMap.)
                              – Stephen C
                              Sep 9 '13 at 8:16




                              6) Hashtable does not guarantee that the order of map elements will be stable over time either. (You are perhaps confusing Hashtable with LinkedHashMap.)
                              – Stephen C
                              Sep 9 '13 at 8:16




                              3




                              3




                              Anyone else really worried that students these days are getting the errant idea that getting "synchronized versions" of the collections somehow means that you don't have to externally synchronize compound operations? My favorite example of this being thing.set(thing.get() + 1); which more often than not catches newbies by surprise as completely unprotected, especially if the get() and set() are synchronized methods. Many of them are expecting magic.
                              – user4229245
                              May 4 '15 at 22:26






                              Anyone else really worried that students these days are getting the errant idea that getting "synchronized versions" of the collections somehow means that you don't have to externally synchronize compound operations? My favorite example of this being thing.set(thing.get() + 1); which more often than not catches newbies by surprise as completely unprotected, especially if the get() and set() are synchronized methods. Many of them are expecting magic.
                              – user4229245
                              May 4 '15 at 22:26














                              Iterators on HashMap is not fail-safe
                              – Abdul
                              Jul 30 '18 at 1:56




                              Iterators on HashMap is not fail-safe
                              – Abdul
                              Jul 30 '18 at 1:56











                              113














                              HashMap: An implementation of the Map interface that uses hash codes to index an array.
                              Hashtable: Hi, 1998 called. They want their collections API back.



                              Seriously though, you're better off staying away from Hashtable 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 ConcurrentHashMap instead.






                              share|improve this answer























                              • This actually makes sense. ConcurrentHashMaps gives you freedom of synchronization and debugging is lot more easier.
                                – prap19
                                Nov 19 '11 at 14:55






                              • 1




                                Is this specific to Java or all the hash map implementation.
                                – Goutam
                                Sep 1 '18 at 19:23
















                              113














                              HashMap: An implementation of the Map interface that uses hash codes to index an array.
                              Hashtable: Hi, 1998 called. They want their collections API back.



                              Seriously though, you're better off staying away from Hashtable 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 ConcurrentHashMap instead.






                              share|improve this answer























                              • This actually makes sense. ConcurrentHashMaps gives you freedom of synchronization and debugging is lot more easier.
                                – prap19
                                Nov 19 '11 at 14:55






                              • 1




                                Is this specific to Java or all the hash map implementation.
                                – Goutam
                                Sep 1 '18 at 19:23














                              113












                              113








                              113






                              HashMap: An implementation of the Map interface that uses hash codes to index an array.
                              Hashtable: Hi, 1998 called. They want their collections API back.



                              Seriously though, you're better off staying away from Hashtable 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 ConcurrentHashMap instead.






                              share|improve this answer














                              HashMap: An implementation of the Map interface that uses hash codes to index an array.
                              Hashtable: Hi, 1998 called. They want their collections API back.



                              Seriously though, you're better off staying away from Hashtable 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 ConcurrentHashMap instead.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Dec 4 '17 at 21:31

























                              answered Sep 2 '08 at 23:14









                              Apocalisp

                              31.1k693146




                              31.1k693146












                              • This actually makes sense. ConcurrentHashMaps gives you freedom of synchronization and debugging is lot more easier.
                                – prap19
                                Nov 19 '11 at 14:55






                              • 1




                                Is this specific to Java or all the hash map implementation.
                                – Goutam
                                Sep 1 '18 at 19:23


















                              • This actually makes sense. ConcurrentHashMaps gives you freedom of synchronization and debugging is lot more easier.
                                – prap19
                                Nov 19 '11 at 14:55






                              • 1




                                Is this specific to Java or all the hash map implementation.
                                – Goutam
                                Sep 1 '18 at 19:23
















                              This actually makes sense. ConcurrentHashMaps gives you freedom of synchronization and debugging is lot more easier.
                              – prap19
                              Nov 19 '11 at 14:55




                              This actually makes sense. ConcurrentHashMaps gives you freedom of synchronization and debugging is lot more easier.
                              – prap19
                              Nov 19 '11 at 14:55




                              1




                              1




                              Is this specific to Java or all the hash map implementation.
                              – Goutam
                              Sep 1 '18 at 19:23




                              Is this specific to Java or all the hash map implementation.
                              – Goutam
                              Sep 1 '18 at 19:23











                              111














                              Keep in mind that HashTable was legacy class before Java Collections Framework (JCF) was introduced and was later retrofitted to implement the Map interface. So was Vector and Stack.



                              Therefore, always stay away from them in new code since there always better alternative in the JCF as others had pointed out.



                              Here is the Java collection cheat sheet that you will find useful. Notice the gray block contains the legacy class HashTable,Vector and Stack.



                              enter image description here






                              share|improve this answer




























                                111














                                Keep in mind that HashTable was legacy class before Java Collections Framework (JCF) was introduced and was later retrofitted to implement the Map interface. So was Vector and Stack.



                                Therefore, always stay away from them in new code since there always better alternative in the JCF as others had pointed out.



                                Here is the Java collection cheat sheet that you will find useful. Notice the gray block contains the legacy class HashTable,Vector and Stack.



                                enter image description here






                                share|improve this answer


























                                  111












                                  111








                                  111






                                  Keep in mind that HashTable was legacy class before Java Collections Framework (JCF) was introduced and was later retrofitted to implement the Map interface. So was Vector and Stack.



                                  Therefore, always stay away from them in new code since there always better alternative in the JCF as others had pointed out.



                                  Here is the Java collection cheat sheet that you will find useful. Notice the gray block contains the legacy class HashTable,Vector and Stack.



                                  enter image description here






                                  share|improve this answer














                                  Keep in mind that HashTable was legacy class before Java Collections Framework (JCF) was introduced and was later retrofitted to implement the Map interface. So was Vector and Stack.



                                  Therefore, always stay away from them in new code since there always better alternative in the JCF as others had pointed out.



                                  Here is the Java collection cheat sheet that you will find useful. Notice the gray block contains the legacy class HashTable,Vector and Stack.



                                  enter image description here







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jun 3 '15 at 5:43









                                  Pratik Khadloya

                                  7,65645876




                                  7,65645876










                                  answered Mar 25 '14 at 8:58









                                  pierrotlefou

                                  19.5k27120159




                                  19.5k27120159























                                      59














                                      In addition to what izb said, HashMap allows null values, whereas the Hashtable does not.



                                      Also note that Hashtable extends the Dictionary class, which as the Javadocs state, is obsolete and has been replaced by the Map interface.






                                      share|improve this answer

















                                      • 3




                                        but that does not make the HashTable obsolete does it?
                                        – Pacerier
                                        Nov 1 '11 at 20:22
















                                      59














                                      In addition to what izb said, HashMap allows null values, whereas the Hashtable does not.



                                      Also note that Hashtable extends the Dictionary class, which as the Javadocs state, is obsolete and has been replaced by the Map interface.






                                      share|improve this answer

















                                      • 3




                                        but that does not make the HashTable obsolete does it?
                                        – Pacerier
                                        Nov 1 '11 at 20:22














                                      59












                                      59








                                      59






                                      In addition to what izb said, HashMap allows null values, whereas the Hashtable does not.



                                      Also note that Hashtable extends the Dictionary class, which as the Javadocs state, is obsolete and has been replaced by the Map interface.






                                      share|improve this answer












                                      In addition to what izb said, HashMap allows null values, whereas the Hashtable does not.



                                      Also note that Hashtable extends the Dictionary class, which as the Javadocs state, is obsolete and has been replaced by the Map interface.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Sep 2 '08 at 20:30









                                      matt b

                                      110k58251320




                                      110k58251320








                                      • 3




                                        but that does not make the HashTable obsolete does it?
                                        – Pacerier
                                        Nov 1 '11 at 20:22














                                      • 3




                                        but that does not make the HashTable obsolete does it?
                                        – Pacerier
                                        Nov 1 '11 at 20:22








                                      3




                                      3




                                      but that does not make the HashTable obsolete does it?
                                      – Pacerier
                                      Nov 1 '11 at 20:22




                                      but that does not make the HashTable obsolete does it?
                                      – Pacerier
                                      Nov 1 '11 at 20:22











                                      51














                                      Take a look at this chart. It provides comparisons between different data structures along with HashMap and Hashtable. The comparison is precise, clear and easy to understand.



                                      Java Collection Matrix






                                      share|improve this answer























                                      • thanks, now I know what to choose in my scenario.
                                        – Well Smith
                                        Apr 15 '18 at 3:17
















                                      51














                                      Take a look at this chart. It provides comparisons between different data structures along with HashMap and Hashtable. The comparison is precise, clear and easy to understand.



                                      Java Collection Matrix






                                      share|improve this answer























                                      • thanks, now I know what to choose in my scenario.
                                        – Well Smith
                                        Apr 15 '18 at 3:17














                                      51












                                      51








                                      51






                                      Take a look at this chart. It provides comparisons between different data structures along with HashMap and Hashtable. The comparison is precise, clear and easy to understand.



                                      Java Collection Matrix






                                      share|improve this answer














                                      Take a look at this chart. It provides comparisons between different data structures along with HashMap and Hashtable. The comparison is precise, clear and easy to understand.



                                      Java Collection Matrix







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited May 15 '13 at 3:36

























                                      answered Nov 20 '12 at 5:35









                                      Sujan

                                      99521638




                                      99521638












                                      • thanks, now I know what to choose in my scenario.
                                        – Well Smith
                                        Apr 15 '18 at 3:17


















                                      • thanks, now I know what to choose in my scenario.
                                        – Well Smith
                                        Apr 15 '18 at 3:17
















                                      thanks, now I know what to choose in my scenario.
                                      – Well Smith
                                      Apr 15 '18 at 3:17




                                      thanks, now I know what to choose in my scenario.
                                      – Well Smith
                                      Apr 15 '18 at 3:17











                                      46














                                      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?



                                      enter image description here






                                      share|improve this answer























                                      • Pretty much covered in this answer (dupicate of )- stackoverflow.com/a/39785829/432903.
                                        – prayagupd
                                        Mar 13 '17 at 2:36












                                      • Why do you say ~"Hashtable is a legacy class"? Where is the supporting documentation for that.
                                        – IgorGanapolsky
                                        Mar 24 '17 at 19:29






                                      • 2




                                        @IgorGanapolsky you may read this - stackoverflow.com/questions/21086307/…
                                        – roottraveller
                                        Mar 29 '17 at 9:48










                                      • Maintaining HashMap is costly than TreeMap. Because HashMap creates unnecessary extra buckets.
                                        – Abdul
                                        Jul 30 '18 at 2:05
















                                      46














                                      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?



                                      enter image description here






                                      share|improve this answer























                                      • Pretty much covered in this answer (dupicate of )- stackoverflow.com/a/39785829/432903.
                                        – prayagupd
                                        Mar 13 '17 at 2:36












                                      • Why do you say ~"Hashtable is a legacy class"? Where is the supporting documentation for that.
                                        – IgorGanapolsky
                                        Mar 24 '17 at 19:29






                                      • 2




                                        @IgorGanapolsky you may read this - stackoverflow.com/questions/21086307/…
                                        – roottraveller
                                        Mar 29 '17 at 9:48










                                      • Maintaining HashMap is costly than TreeMap. Because HashMap creates unnecessary extra buckets.
                                        – Abdul
                                        Jul 30 '18 at 2:05














                                      46












                                      46








                                      46






                                      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?



                                      enter image description here






                                      share|improve this answer














                                      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?



                                      enter image description here







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Aug 16 '18 at 12:23









                                      Karthikeyan Vaithilingam

                                      4,54473047




                                      4,54473047










                                      answered Mar 6 '17 at 10:09









                                      roottraveller

                                      3,88933440




                                      3,88933440












                                      • Pretty much covered in this answer (dupicate of )- stackoverflow.com/a/39785829/432903.
                                        – prayagupd
                                        Mar 13 '17 at 2:36












                                      • Why do you say ~"Hashtable is a legacy class"? Where is the supporting documentation for that.
                                        – IgorGanapolsky
                                        Mar 24 '17 at 19:29






                                      • 2




                                        @IgorGanapolsky you may read this - stackoverflow.com/questions/21086307/…
                                        – roottraveller
                                        Mar 29 '17 at 9:48










                                      • Maintaining HashMap is costly than TreeMap. Because HashMap creates unnecessary extra buckets.
                                        – Abdul
                                        Jul 30 '18 at 2:05


















                                      • Pretty much covered in this answer (dupicate of )- stackoverflow.com/a/39785829/432903.
                                        – prayagupd
                                        Mar 13 '17 at 2:36












                                      • Why do you say ~"Hashtable is a legacy class"? Where is the supporting documentation for that.
                                        – IgorGanapolsky
                                        Mar 24 '17 at 19:29






                                      • 2




                                        @IgorGanapolsky you may read this - stackoverflow.com/questions/21086307/…
                                        – roottraveller
                                        Mar 29 '17 at 9:48










                                      • Maintaining HashMap is costly than TreeMap. Because HashMap creates unnecessary extra buckets.
                                        – Abdul
                                        Jul 30 '18 at 2:05
















                                      Pretty much covered in this answer (dupicate of )- stackoverflow.com/a/39785829/432903.
                                      – prayagupd
                                      Mar 13 '17 at 2:36






                                      Pretty much covered in this answer (dupicate of )- stackoverflow.com/a/39785829/432903.
                                      – prayagupd
                                      Mar 13 '17 at 2:36














                                      Why do you say ~"Hashtable is a legacy class"? Where is the supporting documentation for that.
                                      – IgorGanapolsky
                                      Mar 24 '17 at 19:29




                                      Why do you say ~"Hashtable is a legacy class"? Where is the supporting documentation for that.
                                      – IgorGanapolsky
                                      Mar 24 '17 at 19:29




                                      2




                                      2




                                      @IgorGanapolsky you may read this - stackoverflow.com/questions/21086307/…
                                      – roottraveller
                                      Mar 29 '17 at 9:48




                                      @IgorGanapolsky you may read this - stackoverflow.com/questions/21086307/…
                                      – roottraveller
                                      Mar 29 '17 at 9:48












                                      Maintaining HashMap is costly than TreeMap. Because HashMap creates unnecessary extra buckets.
                                      – Abdul
                                      Jul 30 '18 at 2:05




                                      Maintaining HashMap is costly than TreeMap. Because HashMap creates unnecessary extra buckets.
                                      – Abdul
                                      Jul 30 '18 at 2:05











                                      41














                                      Hashtable is similar to the HashMap and has a similar interface. It is recommended that you use HashMap, unless you require support for legacy applications or you need synchronisation, as the Hashtables methods are synchronised. So in your case as you are not multi-threading, HashMaps are your best bet.






                                      share|improve this answer




























                                        41














                                        Hashtable is similar to the HashMap and has a similar interface. It is recommended that you use HashMap, unless you require support for legacy applications or you need synchronisation, as the Hashtables methods are synchronised. So in your case as you are not multi-threading, HashMaps are your best bet.






                                        share|improve this answer


























                                          41












                                          41








                                          41






                                          Hashtable is similar to the HashMap and has a similar interface. It is recommended that you use HashMap, unless you require support for legacy applications or you need synchronisation, as the Hashtables methods are synchronised. So in your case as you are not multi-threading, HashMaps are your best bet.






                                          share|improve this answer














                                          Hashtable is similar to the HashMap and has a similar interface. It is recommended that you use HashMap, unless you require support for legacy applications or you need synchronisation, as the Hashtables methods are synchronised. So in your case as you are not multi-threading, HashMaps are your best bet.







                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Mar 2 '15 at 8:55









                                          nbro

                                          5,56584893




                                          5,56584893










                                          answered Sep 2 '08 at 20:25









                                          Miles D

                                          4,99252835




                                          4,99252835























                                              31














                                              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






                                              share|improve this answer


























                                                31














                                                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






                                                share|improve this answer
























                                                  31












                                                  31








                                                  31






                                                  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






                                                  share|improve this answer












                                                  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







                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Sep 8 '11 at 6:40









                                                  Neerja

                                                  31132




                                                  31132























                                                      30














                                                      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.



                                                      For example, compare Java 5 Map iterating:



                                                      for (Elem elem : map.keys()) {
                                                      elem.doSth();
                                                      }


                                                      versus the old Hashtable approach:



                                                      for (Enumeration en = htable.keys(); en.hasMoreElements(); ) {
                                                      Elem elem = (Elem) en.nextElement();
                                                      elem.doSth();
                                                      }


                                                      In Java 1.8 we are also promised to be able to construct and access HashMaps like in good old scripting languages:



                                                      Map<String,Integer> map = { "orange" : 12, "apples" : 15 };
                                                      map["apples"];


                                                      Update: No, they won't land in 1.8... :(



                                                      Are Project Coin's collection enhancements going to be in JDK8?






                                                      share|improve this answer




























                                                        30














                                                        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.



                                                        For example, compare Java 5 Map iterating:



                                                        for (Elem elem : map.keys()) {
                                                        elem.doSth();
                                                        }


                                                        versus the old Hashtable approach:



                                                        for (Enumeration en = htable.keys(); en.hasMoreElements(); ) {
                                                        Elem elem = (Elem) en.nextElement();
                                                        elem.doSth();
                                                        }


                                                        In Java 1.8 we are also promised to be able to construct and access HashMaps like in good old scripting languages:



                                                        Map<String,Integer> map = { "orange" : 12, "apples" : 15 };
                                                        map["apples"];


                                                        Update: No, they won't land in 1.8... :(



                                                        Are Project Coin's collection enhancements going to be in JDK8?






                                                        share|improve this answer


























                                                          30












                                                          30








                                                          30






                                                          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.



                                                          For example, compare Java 5 Map iterating:



                                                          for (Elem elem : map.keys()) {
                                                          elem.doSth();
                                                          }


                                                          versus the old Hashtable approach:



                                                          for (Enumeration en = htable.keys(); en.hasMoreElements(); ) {
                                                          Elem elem = (Elem) en.nextElement();
                                                          elem.doSth();
                                                          }


                                                          In Java 1.8 we are also promised to be able to construct and access HashMaps like in good old scripting languages:



                                                          Map<String,Integer> map = { "orange" : 12, "apples" : 15 };
                                                          map["apples"];


                                                          Update: No, they won't land in 1.8... :(



                                                          Are Project Coin's collection enhancements going to be in JDK8?






                                                          share|improve this answer














                                                          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.



                                                          For example, compare Java 5 Map iterating:



                                                          for (Elem elem : map.keys()) {
                                                          elem.doSth();
                                                          }


                                                          versus the old Hashtable approach:



                                                          for (Enumeration en = htable.keys(); en.hasMoreElements(); ) {
                                                          Elem elem = (Elem) en.nextElement();
                                                          elem.doSth();
                                                          }


                                                          In Java 1.8 we are also promised to be able to construct and access HashMaps like in good old scripting languages:



                                                          Map<String,Integer> map = { "orange" : 12, "apples" : 15 };
                                                          map["apples"];


                                                          Update: No, they won't land in 1.8... :(



                                                          Are Project Coin's collection enhancements going to be in JDK8?







                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited May 23 '17 at 12:34









                                                          Community

                                                          11




                                                          11










                                                          answered Jan 12 '12 at 9:17









                                                          pwes

                                                          1,5241826




                                                          1,5241826























                                                              26
















                                                              • HashTable is synchronized, if you are using it in a single thread you can use HashMap, 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.
                                                                Youn can wrap a unsynchronized map in a synchronized one using :



                                                                Map m = Collections.synchronizedMap(new HashMap(...));


                                                              • HashTable can only contain non-null object as a key or as a value. HashMap can contain one null key and null values.


                                                              • 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 ConcurrentModificationException. 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. Whereas the Enumerations returned by Hashtable's keys and elements methods are not fail-fast.


                                                              • HashTable and HashMap are member of the Java Collections Framework (since Java 2 platform v1.2, HashTable was retrofitted to implement the Map interface).


                                                              • HashTable is considered legacy code, the documentation advise to use ConcurrentHashMap in place of Hashtable if a thread-safe highly-concurrent implementation is desired.


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







                                                              share|improve this answer


























                                                                26
















                                                                • HashTable is synchronized, if you are using it in a single thread you can use HashMap, 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.
                                                                  Youn can wrap a unsynchronized map in a synchronized one using :



                                                                  Map m = Collections.synchronizedMap(new HashMap(...));


                                                                • HashTable can only contain non-null object as a key or as a value. HashMap can contain one null key and null values.


                                                                • 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 ConcurrentModificationException. 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. Whereas the Enumerations returned by Hashtable's keys and elements methods are not fail-fast.


                                                                • HashTable and HashMap are member of the Java Collections Framework (since Java 2 platform v1.2, HashTable was retrofitted to implement the Map interface).


                                                                • HashTable is considered legacy code, the documentation advise to use ConcurrentHashMap in place of Hashtable if a thread-safe highly-concurrent implementation is desired.


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







                                                                share|improve this answer
























                                                                  26












                                                                  26








                                                                  26








                                                                  • HashTable is synchronized, if you are using it in a single thread you can use HashMap, 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.
                                                                    Youn can wrap a unsynchronized map in a synchronized one using :



                                                                    Map m = Collections.synchronizedMap(new HashMap(...));


                                                                  • HashTable can only contain non-null object as a key or as a value. HashMap can contain one null key and null values.


                                                                  • 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 ConcurrentModificationException. 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. Whereas the Enumerations returned by Hashtable's keys and elements methods are not fail-fast.


                                                                  • HashTable and HashMap are member of the Java Collections Framework (since Java 2 platform v1.2, HashTable was retrofitted to implement the Map interface).


                                                                  • HashTable is considered legacy code, the documentation advise to use ConcurrentHashMap in place of Hashtable if a thread-safe highly-concurrent implementation is desired.


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







                                                                  share|improve this answer














                                                                  • HashTable is synchronized, if you are using it in a single thread you can use HashMap, 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.
                                                                    Youn can wrap a unsynchronized map in a synchronized one using :



                                                                    Map m = Collections.synchronizedMap(new HashMap(...));


                                                                  • HashTable can only contain non-null object as a key or as a value. HashMap can contain one null key and null values.


                                                                  • 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 ConcurrentModificationException. 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. Whereas the Enumerations returned by Hashtable's keys and elements methods are not fail-fast.


                                                                  • HashTable and HashMap are member of the Java Collections Framework (since Java 2 platform v1.2, HashTable was retrofitted to implement the Map interface).


                                                                  • HashTable is considered legacy code, the documentation advise to use ConcurrentHashMap in place of Hashtable if a thread-safe highly-concurrent implementation is desired.


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








                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Apr 29 '12 at 13:57









                                                                  alain.janinm

                                                                  16.5k94489




                                                                  16.5k94489























                                                                      25














                                                                      HashMap and Hashtable have significant algorithmic differences as well. No one has mentioned this before so that's why I am bringing it up. HashMap 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 Hashtable 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.



                                                                      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.






                                                                      share|improve this answer




























                                                                        25














                                                                        HashMap and Hashtable have significant algorithmic differences as well. No one has mentioned this before so that's why I am bringing it up. HashMap 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 Hashtable 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.



                                                                        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.






                                                                        share|improve this answer


























                                                                          25












                                                                          25








                                                                          25






                                                                          HashMap and Hashtable have significant algorithmic differences as well. No one has mentioned this before so that's why I am bringing it up. HashMap 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 Hashtable 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.



                                                                          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.






                                                                          share|improve this answer














                                                                          HashMap and Hashtable have significant algorithmic differences as well. No one has mentioned this before so that's why I am bringing it up. HashMap 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 Hashtable 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.



                                                                          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.







                                                                          share|improve this answer














                                                                          share|improve this answer



                                                                          share|improve this answer








                                                                          edited Jan 24 '14 at 8:35

























                                                                          answered Dec 10 '12 at 8:57









                                                                          SkyWalker

                                                                          5,218842101




                                                                          5,218842101























                                                                              22














                                                                              Hashtable is synchronized, whereas HashMap isn't. That makes Hashtable slower than Hashmap.



                                                                              For non-threaded apps, use HashMap since they are otherwise the same in terms of functionality.






                                                                              share|improve this answer


























                                                                                22














                                                                                Hashtable is synchronized, whereas HashMap isn't. That makes Hashtable slower than Hashmap.



                                                                                For non-threaded apps, use HashMap since they are otherwise the same in terms of functionality.






                                                                                share|improve this answer
























                                                                                  22












                                                                                  22








                                                                                  22






                                                                                  Hashtable is synchronized, whereas HashMap isn't. That makes Hashtable slower than Hashmap.



                                                                                  For non-threaded apps, use HashMap since they are otherwise the same in terms of functionality.






                                                                                  share|improve this answer












                                                                                  Hashtable is synchronized, whereas HashMap isn't. That makes Hashtable slower than Hashmap.



                                                                                  For non-threaded apps, use HashMap since they are otherwise the same in terms of functionality.







                                                                                  share|improve this answer












                                                                                  share|improve this answer



                                                                                  share|improve this answer










                                                                                  answered Sep 2 '08 at 20:22









                                                                                  izb

                                                                                  23.9k3097157




                                                                                  23.9k3097157























                                                                                      21














                                                                                      Based on the info here, 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.






                                                                                      share|improve this answer

















                                                                                      • 5




                                                                                        It doesn't actually prevent it, it just detects it and throws an error.
                                                                                        – Bart van Heukelom
                                                                                        Dec 18 '10 at 1:44






                                                                                      • 1




                                                                                        I'm pretty sure it will throw a ConncurrentModificationException before the underlying collection is modified, though I could be wrong.
                                                                                        – pkaeding
                                                                                        Jan 1 '11 at 1:46










                                                                                      • It will attempt to detect concurrent modification and throw an exception. But if you're doing anything with threads, it can't make any promises. Absolutely anything can happen, including breakage.
                                                                                        – cHao
                                                                                        Apr 18 '11 at 14:03


















                                                                                      21














                                                                                      Based on the info here, 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.






                                                                                      share|improve this answer

















                                                                                      • 5




                                                                                        It doesn't actually prevent it, it just detects it and throws an error.
                                                                                        – Bart van Heukelom
                                                                                        Dec 18 '10 at 1:44






                                                                                      • 1




                                                                                        I'm pretty sure it will throw a ConncurrentModificationException before the underlying collection is modified, though I could be wrong.
                                                                                        – pkaeding
                                                                                        Jan 1 '11 at 1:46










                                                                                      • It will attempt to detect concurrent modification and throw an exception. But if you're doing anything with threads, it can't make any promises. Absolutely anything can happen, including breakage.
                                                                                        – cHao
                                                                                        Apr 18 '11 at 14:03
















                                                                                      21












                                                                                      21








                                                                                      21






                                                                                      Based on the info here, 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.






                                                                                      share|improve this answer












                                                                                      Based on the info here, 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.







                                                                                      share|improve this answer












                                                                                      share|improve this answer



                                                                                      share|improve this answer










                                                                                      answered Sep 2 '08 at 20:14









                                                                                      pkaeding

                                                                                      24.2k2585130




                                                                                      24.2k2585130








                                                                                      • 5




                                                                                        It doesn't actually prevent it, it just detects it and throws an error.
                                                                                        – Bart van Heukelom
                                                                                        Dec 18 '10 at 1:44






                                                                                      • 1




                                                                                        I'm pretty sure it will throw a ConncurrentModificationException before the underlying collection is modified, though I could be wrong.
                                                                                        – pkaeding
                                                                                        Jan 1 '11 at 1:46










                                                                                      • It will attempt to detect concurrent modification and throw an exception. But if you're doing anything with threads, it can't make any promises. Absolutely anything can happen, including breakage.
                                                                                        – cHao
                                                                                        Apr 18 '11 at 14:03
















                                                                                      • 5




                                                                                        It doesn't actually prevent it, it just detects it and throws an error.
                                                                                        – Bart van Heukelom
                                                                                        Dec 18 '10 at 1:44






                                                                                      • 1




                                                                                        I'm pretty sure it will throw a ConncurrentModificationException before the underlying collection is modified, though I could be wrong.
                                                                                        – pkaeding
                                                                                        Jan 1 '11 at 1:46










                                                                                      • It will attempt to detect concurrent modification and throw an exception. But if you're doing anything with threads, it can't make any promises. Absolutely anything can happen, including breakage.
                                                                                        – cHao
                                                                                        Apr 18 '11 at 14:03










                                                                                      5




                                                                                      5




                                                                                      It doesn't actually prevent it, it just detects it and throws an error.
                                                                                      – Bart van Heukelom
                                                                                      Dec 18 '10 at 1:44




                                                                                      It doesn't actually prevent it, it just detects it and throws an error.
                                                                                      – Bart van Heukelom
                                                                                      Dec 18 '10 at 1:44




                                                                                      1




                                                                                      1




                                                                                      I'm pretty sure it will throw a ConncurrentModificationException before the underlying collection is modified, though I could be wrong.
                                                                                      – pkaeding
                                                                                      Jan 1 '11 at 1:46




                                                                                      I'm pretty sure it will throw a ConncurrentModificationException before the underlying collection is modified, though I could be wrong.
                                                                                      – pkaeding
                                                                                      Jan 1 '11 at 1:46












                                                                                      It will attempt to detect concurrent modification and throw an exception. But if you're doing anything with threads, it can't make any promises. Absolutely anything can happen, including breakage.
                                                                                      – cHao
                                                                                      Apr 18 '11 at 14:03






                                                                                      It will attempt to detect concurrent modification and throw an exception. But if you're doing anything with threads, it can't make any promises. Absolutely anything can happen, including breakage.
                                                                                      – cHao
                                                                                      Apr 18 '11 at 14:03













                                                                                      18














                                                                                      A Collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. A collections framework W is a unified architecture for representing and manipulating collections.



                                                                                      The HashMap JDK1.2 and Hashtable JDK1.0, both are used to represent a group of objects that are represented in <Key, Value> pair. Each <Key, Value> pair is called Entry object. The collection of Entries is referred by the object of HashMap and Hashtable. 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.]





                                                                                      « Superclass, Legacy and Collection Framework member



                                                                                      Hashtable is a legacy class introduced in JDK1.0, which is a subclass of Dictionary class. From JDK1.2 Hashtable is re-engineered to implement the Map interface to make a member of collection framework. HashMap is a member of Java Collection Framework right from the beginning of its introduction in JDK1.2. HashMap is the subclass of the AbstractMap class.





                                                                                      public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable { ... }

                                                                                      public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { ... }




                                                                                      « Initial capacity and Load factor



                                                                                      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 "hashcollision", 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.



                                                                                      HashMap constructs an empty hash table with the default initial capacity (16) and the default load factor (0.75). Where as Hashtable constructs empty hashtable with a default initial capacity (11) and load factor/fill ratio (0.75).



                                                                                      Hash Map & Hashtable



                                                                                      « Structural modification in case of hash collision



                                                                                      HashMap, Hashtable in case of hash collisions they store the map entries in linked lists. From Java8 for HashMap if hash bucket grows beyond a certain threshold, that bucket will switch from linked list of entries to a balanced tree. 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, HashMap 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 HashMap comparable. On adding entries if bucket size reaches TREEIFY_THRESHOLD = 8 convert linked list of entries to a balanced tree, on removing entries less than TREEIFY_THRESHOLD and at most UNTREEIFY_THRESHOLD = 6 will reconvert balanced tree to linked list of entries. Java 8 SRC, stackpost



                                                                                      « Collection-view iteration, Fail-Fast and Fail-Safe



                                                                                          +--------------------+-----------+-------------+
                                                                                      | | Iterator | Enumeration |
                                                                                      +--------------------+-----------+-------------+
                                                                                      | Hashtable | fail-fast | safe |
                                                                                      +--------------------+-----------+-------------+
                                                                                      | HashMap | fail-fast | fail-fast |
                                                                                      +--------------------+-----------+-------------+
                                                                                      | ConcurrentHashMap | safe | safe |
                                                                                      +--------------------+-----------+-------------+


                                                                                      Iterator 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 Enumeration is fail-safe in nature. It doesn’t throw any exceptions if a collection is modified while iterating.



                                                                                      According to Java API Docs, Iterator is always preferred over the Enumeration.



                                                                                      NOTE: 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.



                                                                                      In Java 5 introduced ConcurrentMap Interface: ConcurrentHashMap - a highly concurrent, high-performance ConcurrentMap 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 Hashtable: in addition to implementing ConcurrentMap, it supports all of the "legacy" methods peculiar to Hashtable.




                                                                                      • Each HashMapEntrys value is volatile thereby ensuring fine grain consistency for contended modifications and subsequent reads; each read reflects the most recently completed update


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


                                                                                      • Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.



                                                                                      public static void main(String args) {

                                                                                      //HashMap<String, Integer> hash = new HashMap<String, Integer>();
                                                                                      Hashtable<String, Integer> hash = new Hashtable<String, Integer>();
                                                                                      //ConcurrentHashMap<String, Integer> hash = new ConcurrentHashMap<>();

                                                                                      new Thread() {
                                                                                      @Override public void run() {
                                                                                      try {
                                                                                      for (int i = 10; i < 20; i++) {
                                                                                      sleepThread(1);
                                                                                      System.out.println("T1 :- Key"+i);
                                                                                      hash.put("Key"+i, i);
                                                                                      }
                                                                                      System.out.println( System.identityHashCode( hash ) );
                                                                                      } catch ( Exception e ) {
                                                                                      e.printStackTrace();
                                                                                      }
                                                                                      }
                                                                                      }.start();
                                                                                      new Thread() {
                                                                                      @Override public void run() {
                                                                                      try {
                                                                                      sleepThread(5);
                                                                                      // ConcurrentHashMap traverse using Iterator, Enumeration is Fail-Safe.

                                                                                      // Hashtable traverse using Enumeration is Fail-Safe, Iterator is Fail-Fast.
                                                                                      for (Enumeration<String> e = hash.keys(); e.hasMoreElements(); ) {
                                                                                      sleepThread(1);
                                                                                      System.out.println("T2 : "+ e.nextElement());
                                                                                      }

                                                                                      // HashMap traverse using Iterator, Enumeration is Fail-Fast.
                                                                                      /*
                                                                                      for (Iterator< Entry<String, Integer> > it = hash.entrySet().iterator(); it.hasNext(); ) {
                                                                                      sleepThread(1);
                                                                                      System.out.println("T2 : "+ it.next());
                                                                                      // ConcurrentModificationException at java.util.Hashtable$Enumerator.next
                                                                                      }
                                                                                      */

                                                                                      /*
                                                                                      Set< Entry<String, Integer> > entrySet = hash.entrySet();
                                                                                      Iterator< Entry<String, Integer> > it = entrySet.iterator();
                                                                                      Enumeration<Entry<String, Integer>> entryEnumeration = Collections.enumeration( entrySet );
                                                                                      while( entryEnumeration.hasMoreElements() ) {
                                                                                      sleepThread(1);
                                                                                      Entry<String, Integer> nextElement = entryEnumeration.nextElement();
                                                                                      System.out.println("T2 : "+ nextElement.getKey() +" : "+ nextElement.getValue() );
                                                                                      //java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextNode
                                                                                      // at java.util.HashMap$EntryIterator.next
                                                                                      // at java.util.Collections$3.nextElement
                                                                                      }
                                                                                      */
                                                                                      } catch ( Exception e ) {
                                                                                      e.printStackTrace();
                                                                                      }
                                                                                      }
                                                                                      }.start();

                                                                                      Map<String, String> unmodifiableMap = Collections.unmodifiableMap( map );
                                                                                      try {
                                                                                      unmodifiableMap.put("key4", "unmodifiableMap");
                                                                                      } catch (java.lang.UnsupportedOperationException e) {
                                                                                      System.err.println("UnsupportedOperationException : "+ e.getMessage() );
                                                                                      }
                                                                                      }
                                                                                      static void sleepThread( int sec ) {
                                                                                      try {
                                                                                      Thread.sleep( 1000 * sec );
                                                                                      } catch (InterruptedException e) {
                                                                                      e.printStackTrace();
                                                                                      }
                                                                                      }




                                                                                      « Null Keys And Null Values



                                                                                      HashMap allows maximum one null key and any number of null values. Where as Hashtable doesn’t allow even a single null key and null value, if the key or value null is then it throws NullPointerException. Example



                                                                                      « Synchronized, Thread Safe



                                                                                      Hashtable is internally synchronized. Therefore, it is very much safe to use Hashtable in multi threaded applications. Where as HashMap is not internally synchronized. Therefore, it is not safe to use HashMap in multi threaded applications without external synchronization. You can externally synchronize HashMap using Collections.synchronizedMap() method.



                                                                                      « Performance



                                                                                      As Hashtable is internally synchronized, this makes Hashtable slightly slower than the HashMap.





                                                                                      @See




                                                                                      • A red–black tree is a kind of self-balancing binary search tree

                                                                                      • Performance Improvement for HashMap in Java 8






                                                                                      share|improve this answer




























                                                                                        18














                                                                                        A Collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. A collections framework W is a unified architecture for representing and manipulating collections.



                                                                                        The HashMap JDK1.2 and Hashtable JDK1.0, both are used to represent a group of objects that are represented in <Key, Value> pair. Each <Key, Value> pair is called Entry object. The collection of Entries is referred by the object of HashMap and Hashtable. 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.]





                                                                                        « Superclass, Legacy and Collection Framework member



                                                                                        Hashtable is a legacy class introduced in JDK1.0, which is a subclass of Dictionary class. From JDK1.2 Hashtable is re-engineered to implement the Map interface to make a member of collection framework. HashMap is a member of Java Collection Framework right from the beginning of its introduction in JDK1.2. HashMap is the subclass of the AbstractMap class.





                                                                                        public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable { ... }

                                                                                        public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { ... }




                                                                                        « Initial capacity and Load factor



                                                                                        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 "hashcollision", 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.



                                                                                        HashMap constructs an empty hash table with the default initial capacity (16) and the default load factor (0.75). Where as Hashtable constructs empty hashtable with a default initial capacity (11) and load factor/fill ratio (0.75).



                                                                                        Hash Map & Hashtable



                                                                                        « Structural modification in case of hash collision



                                                                                        HashMap, Hashtable in case of hash collisions they store the map entries in linked lists. From Java8 for HashMap if hash bucket grows beyond a certain threshold, that bucket will switch from linked list of entries to a balanced tree. 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, HashMap 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 HashMap comparable. On adding entries if bucket size reaches TREEIFY_THRESHOLD = 8 convert linked list of entries to a balanced tree, on removing entries less than TREEIFY_THRESHOLD and at most UNTREEIFY_THRESHOLD = 6 will reconvert balanced tree to linked list of entries. Java 8 SRC, stackpost



                                                                                        « Collection-view iteration, Fail-Fast and Fail-Safe



                                                                                            +--------------------+-----------+-------------+
                                                                                        | | Iterator | Enumeration |
                                                                                        +--------------------+-----------+-------------+
                                                                                        | Hashtable | fail-fast | safe |
                                                                                        +--------------------+-----------+-------------+
                                                                                        | HashMap | fail-fast | fail-fast |
                                                                                        +--------------------+-----------+-------------+
                                                                                        | ConcurrentHashMap | safe | safe |
                                                                                        +--------------------+-----------+-------------+


                                                                                        Iterator 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 Enumeration is fail-safe in nature. It doesn’t throw any exceptions if a collection is modified while iterating.



                                                                                        According to Java API Docs, Iterator is always preferred over the Enumeration.



                                                                                        NOTE: 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.



                                                                                        In Java 5 introduced ConcurrentMap Interface: ConcurrentHashMap - a highly concurrent, high-performance ConcurrentMap 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 Hashtable: in addition to implementing ConcurrentMap, it supports all of the "legacy" methods peculiar to Hashtable.




                                                                                        • Each HashMapEntrys value is volatile thereby ensuring fine grain consistency for contended modifications and subsequent reads; each read reflects the most recently completed update


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


                                                                                        • Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.



                                                                                        public static void main(String args) {

                                                                                        //HashMap<String, Integer> hash = new HashMap<String, Integer>();
                                                                                        Hashtable<String, Integer> hash = new Hashtable<String, Integer>();
                                                                                        //ConcurrentHashMap<String, Integer> hash = new ConcurrentHashMap<>();

                                                                                        new Thread() {
                                                                                        @Override public void run() {
                                                                                        try {
                                                                                        for (int i = 10; i < 20; i++) {
                                                                                        sleepThread(1);
                                                                                        System.out.println("T1 :- Key"+i);
                                                                                        hash.put("Key"+i, i);
                                                                                        }
                                                                                        System.out.println( System.identityHashCode( hash ) );
                                                                                        } catch ( Exception e ) {
                                                                                        e.printStackTrace();
                                                                                        }
                                                                                        }
                                                                                        }.start();
                                                                                        new Thread() {
                                                                                        @Override public void run() {
                                                                                        try {
                                                                                        sleepThread(5);
                                                                                        // ConcurrentHashMap traverse using Iterator, Enumeration is Fail-Safe.

                                                                                        // Hashtable traverse using Enumeration is Fail-Safe, Iterator is Fail-Fast.
                                                                                        for (Enumeration<String> e = hash.keys(); e.hasMoreElements(); ) {
                                                                                        sleepThread(1);
                                                                                        System.out.println("T2 : "+ e.nextElement());
                                                                                        }

                                                                                        // HashMap traverse using Iterator, Enumeration is Fail-Fast.
                                                                                        /*
                                                                                        for (Iterator< Entry<String, Integer> > it = hash.entrySet().iterator(); it.hasNext(); ) {
                                                                                        sleepThread(1);
                                                                                        System.out.println("T2 : "+ it.next());
                                                                                        // ConcurrentModificationException at java.util.Hashtable$Enumerator.next
                                                                                        }
                                                                                        */

                                                                                        /*
                                                                                        Set< Entry<String, Integer> > entrySet = hash.entrySet();
                                                                                        Iterator< Entry<String, Integer> > it = entrySet.iterator();
                                                                                        Enumeration<Entry<String, Integer>> entryEnumeration = Collections.enumeration( entrySet );
                                                                                        while( entryEnumeration.hasMoreElements() ) {
                                                                                        sleepThread(1);
                                                                                        Entry<String, Integer> nextElement = entryEnumeration.nextElement();
                                                                                        System.out.println("T2 : "+ nextElement.getKey() +" : "+ nextElement.getValue() );
                                                                                        //java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextNode
                                                                                        // at java.util.HashMap$EntryIterator.next
                                                                                        // at java.util.Collections$3.nextElement
                                                                                        }
                                                                                        */
                                                                                        } catch ( Exception e ) {
                                                                                        e.printStackTrace();
                                                                                        }
                                                                                        }
                                                                                        }.start();

                                                                                        Map<String, String> unmodifiableMap = Collections.unmodifiableMap( map );
                                                                                        try {
                                                                                        unmodifiableMap.put("key4", "unmodifiableMap");
                                                                                        } catch (java.lang.UnsupportedOperationException e) {
                                                                                        System.err.println("UnsupportedOperationException : "+ e.getMessage() );
                                                                                        }
                                                                                        }
                                                                                        static void sleepThread( int sec ) {
                                                                                        try {
                                                                                        Thread.sleep( 1000 * sec );
                                                                                        } catch (InterruptedException e) {
                                                                                        e.printStackTrace();
                                                                                        }
                                                                                        }




                                                                                        « Null Keys And Null Values



                                                                                        HashMap allows maximum one null key and any number of null values. Where as Hashtable doesn’t allow even a single null key and null value, if the key or value null is then it throws NullPointerException. Example



                                                                                        « Synchronized, Thread Safe



                                                                                        Hashtable is internally synchronized. Therefore, it is very much safe to use Hashtable in multi threaded applications. Where as HashMap is not internally synchronized. Therefore, it is not safe to use HashMap in multi threaded applications without external synchronization. You can externally synchronize HashMap using Collections.synchronizedMap() method.



                                                                                        « Performance



                                                                                        As Hashtable is internally synchronized, this makes Hashtable slightly slower than the HashMap.





                                                                                        @See




                                                                                        • A red–black tree is a kind of self-balancing binary search tree

                                                                                        • Performance Improvement for HashMap in Java 8






                                                                                        share|improve this answer


























                                                                                          18












                                                                                          18








                                                                                          18






                                                                                          A Collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. A collections framework W is a unified architecture for representing and manipulating collections.



                                                                                          The HashMap JDK1.2 and Hashtable JDK1.0, both are used to represent a group of objects that are represented in <Key, Value> pair. Each <Key, Value> pair is called Entry object. The collection of Entries is referred by the object of HashMap and Hashtable. 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.]





                                                                                          « Superclass, Legacy and Collection Framework member



                                                                                          Hashtable is a legacy class introduced in JDK1.0, which is a subclass of Dictionary class. From JDK1.2 Hashtable is re-engineered to implement the Map interface to make a member of collection framework. HashMap is a member of Java Collection Framework right from the beginning of its introduction in JDK1.2. HashMap is the subclass of the AbstractMap class.





                                                                                          public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable { ... }

                                                                                          public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { ... }




                                                                                          « Initial capacity and Load factor



                                                                                          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 "hashcollision", 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.



                                                                                          HashMap constructs an empty hash table with the default initial capacity (16) and the default load factor (0.75). Where as Hashtable constructs empty hashtable with a default initial capacity (11) and load factor/fill ratio (0.75).



                                                                                          Hash Map & Hashtable



                                                                                          « Structural modification in case of hash collision



                                                                                          HashMap, Hashtable in case of hash collisions they store the map entries in linked lists. From Java8 for HashMap if hash bucket grows beyond a certain threshold, that bucket will switch from linked list of entries to a balanced tree. 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, HashMap 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 HashMap comparable. On adding entries if bucket size reaches TREEIFY_THRESHOLD = 8 convert linked list of entries to a balanced tree, on removing entries less than TREEIFY_THRESHOLD and at most UNTREEIFY_THRESHOLD = 6 will reconvert balanced tree to linked list of entries. Java 8 SRC, stackpost



                                                                                          « Collection-view iteration, Fail-Fast and Fail-Safe



                                                                                              +--------------------+-----------+-------------+
                                                                                          | | Iterator | Enumeration |
                                                                                          +--------------------+-----------+-------------+
                                                                                          | Hashtable | fail-fast | safe |
                                                                                          +--------------------+-----------+-------------+
                                                                                          | HashMap | fail-fast | fail-fast |
                                                                                          +--------------------+-----------+-------------+
                                                                                          | ConcurrentHashMap | safe | safe |
                                                                                          +--------------------+-----------+-------------+


                                                                                          Iterator 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 Enumeration is fail-safe in nature. It doesn’t throw any exceptions if a collection is modified while iterating.



                                                                                          According to Java API Docs, Iterator is always preferred over the Enumeration.



                                                                                          NOTE: 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.



                                                                                          In Java 5 introduced ConcurrentMap Interface: ConcurrentHashMap - a highly concurrent, high-performance ConcurrentMap 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 Hashtable: in addition to implementing ConcurrentMap, it supports all of the "legacy" methods peculiar to Hashtable.




                                                                                          • Each HashMapEntrys value is volatile thereby ensuring fine grain consistency for contended modifications and subsequent reads; each read reflects the most recently completed update


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


                                                                                          • Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.



                                                                                          public static void main(String args) {

                                                                                          //HashMap<String, Integer> hash = new HashMap<String, Integer>();
                                                                                          Hashtable<String, Integer> hash = new Hashtable<String, Integer>();
                                                                                          //ConcurrentHashMap<String, Integer> hash = new ConcurrentHashMap<>();

                                                                                          new Thread() {
                                                                                          @Override public void run() {
                                                                                          try {
                                                                                          for (int i = 10; i < 20; i++) {
                                                                                          sleepThread(1);
                                                                                          System.out.println("T1 :- Key"+i);
                                                                                          hash.put("Key"+i, i);
                                                                                          }
                                                                                          System.out.println( System.identityHashCode( hash ) );
                                                                                          } catch ( Exception e ) {
                                                                                          e.printStackTrace();
                                                                                          }
                                                                                          }
                                                                                          }.start();
                                                                                          new Thread() {
                                                                                          @Override public void run() {
                                                                                          try {
                                                                                          sleepThread(5);
                                                                                          // ConcurrentHashMap traverse using Iterator, Enumeration is Fail-Safe.

                                                                                          // Hashtable traverse using Enumeration is Fail-Safe, Iterator is Fail-Fast.
                                                                                          for (Enumeration<String> e = hash.keys(); e.hasMoreElements(); ) {
                                                                                          sleepThread(1);
                                                                                          System.out.println("T2 : "+ e.nextElement());
                                                                                          }

                                                                                          // HashMap traverse using Iterator, Enumeration is Fail-Fast.
                                                                                          /*
                                                                                          for (Iterator< Entry<String, Integer> > it = hash.entrySet().iterator(); it.hasNext(); ) {
                                                                                          sleepThread(1);
                                                                                          System.out.println("T2 : "+ it.next());
                                                                                          // ConcurrentModificationException at java.util.Hashtable$Enumerator.next
                                                                                          }
                                                                                          */

                                                                                          /*
                                                                                          Set< Entry<String, Integer> > entrySet = hash.entrySet();
                                                                                          Iterator< Entry<String, Integer> > it = entrySet.iterator();
                                                                                          Enumeration<Entry<String, Integer>> entryEnumeration = Collections.enumeration( entrySet );
                                                                                          while( entryEnumeration.hasMoreElements() ) {
                                                                                          sleepThread(1);
                                                                                          Entry<String, Integer> nextElement = entryEnumeration.nextElement();
                                                                                          System.out.println("T2 : "+ nextElement.getKey() +" : "+ nextElement.getValue() );
                                                                                          //java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextNode
                                                                                          // at java.util.HashMap$EntryIterator.next
                                                                                          // at java.util.Collections$3.nextElement
                                                                                          }
                                                                                          */
                                                                                          } catch ( Exception e ) {
                                                                                          e.printStackTrace();
                                                                                          }
                                                                                          }
                                                                                          }.start();

                                                                                          Map<String, String> unmodifiableMap = Collections.unmodifiableMap( map );
                                                                                          try {
                                                                                          unmodifiableMap.put("key4", "unmodifiableMap");
                                                                                          } catch (java.lang.UnsupportedOperationException e) {
                                                                                          System.err.println("UnsupportedOperationException : "+ e.getMessage() );
                                                                                          }
                                                                                          }
                                                                                          static void sleepThread( int sec ) {
                                                                                          try {
                                                                                          Thread.sleep( 1000 * sec );
                                                                                          } catch (InterruptedException e) {
                                                                                          e.printStackTrace();
                                                                                          }
                                                                                          }




                                                                                          « Null Keys And Null Values



                                                                                          HashMap allows maximum one null key and any number of null values. Where as Hashtable doesn’t allow even a single null key and null value, if the key or value null is then it throws NullPointerException. Example



                                                                                          « Synchronized, Thread Safe



                                                                                          Hashtable is internally synchronized. Therefore, it is very much safe to use Hashtable in multi threaded applications. Where as HashMap is not internally synchronized. Therefore, it is not safe to use HashMap in multi threaded applications without external synchronization. You can externally synchronize HashMap using Collections.synchronizedMap() method.



                                                                                          « Performance



                                                                                          As Hashtable is internally synchronized, this makes Hashtable slightly slower than the HashMap.





                                                                                          @See




                                                                                          • A red–black tree is a kind of self-balancing binary search tree

                                                                                          • Performance Improvement for HashMap in Java 8






                                                                                          share|improve this answer














                                                                                          A Collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. A collections framework W is a unified architecture for representing and manipulating collections.



                                                                                          The HashMap JDK1.2 and Hashtable JDK1.0, both are used to represent a group of objects that are represented in <Key, Value> pair. Each <Key, Value> pair is called Entry object. The collection of Entries is referred by the object of HashMap and Hashtable. 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.]





                                                                                          « Superclass, Legacy and Collection Framework member



                                                                                          Hashtable is a legacy class introduced in JDK1.0, which is a subclass of Dictionary class. From JDK1.2 Hashtable is re-engineered to implement the Map interface to make a member of collection framework. HashMap is a member of Java Collection Framework right from the beginning of its introduction in JDK1.2. HashMap is the subclass of the AbstractMap class.





                                                                                          public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable { ... }

                                                                                          public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { ... }




                                                                                          « Initial capacity and Load factor



                                                                                          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 "hashcollision", 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.



                                                                                          HashMap constructs an empty hash table with the default initial capacity (16) and the default load factor (0.75). Where as Hashtable constructs empty hashtable with a default initial capacity (11) and load factor/fill ratio (0.75).



                                                                                          Hash Map & Hashtable



                                                                                          « Structural modification in case of hash collision



                                                                                          HashMap, Hashtable in case of hash collisions they store the map entries in linked lists. From Java8 for HashMap if hash bucket grows beyond a certain threshold, that bucket will switch from linked list of entries to a balanced tree. 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, HashMap 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 HashMap comparable. On adding entries if bucket size reaches TREEIFY_THRESHOLD = 8 convert linked list of entries to a balanced tree, on removing entries less than TREEIFY_THRESHOLD and at most UNTREEIFY_THRESHOLD = 6 will reconvert balanced tree to linked list of entries. Java 8 SRC, stackpost



                                                                                          « Collection-view iteration, Fail-Fast and Fail-Safe



                                                                                              +--------------------+-----------+-------------+
                                                                                          | | Iterator | Enumeration |
                                                                                          +--------------------+-----------+-------------+
                                                                                          | Hashtable | fail-fast | safe |
                                                                                          +--------------------+-----------+-------------+
                                                                                          | HashMap | fail-fast | fail-fast |
                                                                                          +--------------------+-----------+-------------+
                                                                                          | ConcurrentHashMap | safe | safe |
                                                                                          +--------------------+-----------+-------------+


                                                                                          Iterator 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 Enumeration is fail-safe in nature. It doesn’t throw any exceptions if a collection is modified while iterating.



                                                                                          According to Java API Docs, Iterator is always preferred over the Enumeration.



                                                                                          NOTE: 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.



                                                                                          In Java 5 introduced ConcurrentMap Interface: ConcurrentHashMap - a highly concurrent, high-performance ConcurrentMap 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 Hashtable: in addition to implementing ConcurrentMap, it supports all of the "legacy" methods peculiar to Hashtable.




                                                                                          • Each HashMapEntrys value is volatile thereby ensuring fine grain consistency for contended modifications and subsequent reads; each read reflects the most recently completed update


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


                                                                                          • Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.



                                                                                          public static void main(String args) {

                                                                                          //HashMap<String, Integer> hash = new HashMap<String, Integer>();
                                                                                          Hashtable<String, Integer> hash = new Hashtable<String, Integer>();
                                                                                          //ConcurrentHashMap<String, Integer> hash = new ConcurrentHashMap<>();

                                                                                          new Thread() {
                                                                                          @Override public void run() {
                                                                                          try {
                                                                                          for (int i = 10; i < 20; i++) {
                                                                                          sleepThread(1);
                                                                                          System.out.println("T1 :- Key"+i);
                                                                                          hash.put("Key"+i, i);
                                                                                          }
                                                                                          System.out.println( System.identityHashCode( hash ) );
                                                                                          } catch ( Exception e ) {
                                                                                          e.printStackTrace();
                                                                                          }
                                                                                          }
                                                                                          }.start();
                                                                                          new Thread() {
                                                                                          @Override public void run() {
                                                                                          try {
                                                                                          sleepThread(5);
                                                                                          // ConcurrentHashMap traverse using Iterator, Enumeration is Fail-Safe.

                                                                                          // Hashtable traverse using Enumeration is Fail-Safe, Iterator is Fail-Fast.
                                                                                          for (Enumeration<String> e = hash.keys(); e.hasMoreElements(); ) {
                                                                                          sleepThread(1);
                                                                                          System.out.println("T2 : "+ e.nextElement());
                                                                                          }

                                                                                          // HashMap traverse using Iterator, Enumeration is Fail-Fast.
                                                                                          /*
                                                                                          for (Iterator< Entry<String, Integer> > it = hash.entrySet().iterator(); it.hasNext(); ) {
                                                                                          sleepThread(1);
                                                                                          System.out.println("T2 : "+ it.next());
                                                                                          // ConcurrentModificationException at java.util.Hashtable$Enumerator.next
                                                                                          }
                                                                                          */

                                                                                          /*
                                                                                          Set< Entry<String, Integer> > entrySet = hash.entrySet();
                                                                                          Iterator< Entry<String, Integer> > it = entrySet.iterator();
                                                                                          Enumeration<Entry<String, Integer>> entryEnumeration = Collections.enumeration( entrySet );
                                                                                          while( entryEnumeration.hasMoreElements() ) {
                                                                                          sleepThread(1);
                                                                                          Entry<String, Integer> nextElement = entryEnumeration.nextElement();
                                                                                          System.out.println("T2 : "+ nextElement.getKey() +" : "+ nextElement.getValue() );
                                                                                          //java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextNode
                                                                                          // at java.util.HashMap$EntryIterator.next
                                                                                          // at java.util.Collections$3.nextElement
                                                                                          }
                                                                                          */
                                                                                          } catch ( Exception e ) {
                                                                                          e.printStackTrace();
                                                                                          }
                                                                                          }
                                                                                          }.start();

                                                                                          Map<String, String> unmodifiableMap = Collections.unmodifiableMap( map );
                                                                                          try {
                                                                                          unmodifiableMap.put("key4", "unmodifiableMap");
                                                                                          } catch (java.lang.UnsupportedOperationException e) {
                                                                                          System.err.println("UnsupportedOperationException : "+ e.getMessage() );
                                                                                          }
                                                                                          }
                                                                                          static void sleepThread( int sec ) {
                                                                                          try {
                                                                                          Thread.sleep( 1000 * sec );
                                                                                          } catch (InterruptedException e) {
                                                                                          e.printStackTrace();
                                                                                          }
                                                                                          }




                                                                                          « Null Keys And Null Values



                                                                                          HashMap allows maximum one null key and any number of null values. Where as Hashtable doesn’t allow even a single null key and null value, if the key or value null is then it throws NullPointerException. Example



                                                                                          « Synchronized, Thread Safe



                                                                                          Hashtable is internally synchronized. Therefore, it is very much safe to use Hashtable in multi threaded applications. Where as HashMap is not internally synchronized. Therefore, it is not safe to use HashMap in multi threaded applications without external synchronization. You can externally synchronize HashMap using Collections.synchronizedMap() method.



                                                                                          « Performance



                                                                                          As Hashtable is internally synchronized, this makes Hashtable slightly slower than the HashMap.





                                                                                          @See




                                                                                          • A red–black tree is a kind of self-balancing binary search tree

                                                                                          • Performance Improvement for HashMap in Java 8







                                                                                          share|improve this answer














                                                                                          share|improve this answer



                                                                                          share|improve this answer








                                                                                          edited Apr 20 '18 at 16:46









                                                                                          Lonely Neuron

                                                                                          2,86731732




                                                                                          2,86731732










                                                                                          answered Jan 4 '18 at 11:58









                                                                                          Yash

                                                                                          4,31712640




                                                                                          4,31712640























                                                                                              15














                                                                                              For threaded apps, you can often get away with ConcurrentHashMap- depends on your performance requirements.






                                                                                              share|improve this answer


























                                                                                                15














                                                                                                For threaded apps, you can often get away with ConcurrentHashMap- depends on your performance requirements.






                                                                                                share|improve this answer
























                                                                                                  15












                                                                                                  15








                                                                                                  15






                                                                                                  For threaded apps, you can often get away with ConcurrentHashMap- depends on your performance requirements.






                                                                                                  share|improve this answer












                                                                                                  For threaded apps, you can often get away with ConcurrentHashMap- depends on your performance requirements.







                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Sep 2 '08 at 22:38









                                                                                                  Tim Howland

                                                                                                  6,67332244




                                                                                                  6,67332244























                                                                                                      14














                                                                                                      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.






                                                                                                      share|improve this answer


























                                                                                                        14














                                                                                                        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.






                                                                                                        share|improve this answer
























                                                                                                          14












                                                                                                          14








                                                                                                          14






                                                                                                          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.






                                                                                                          share|improve this answer












                                                                                                          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.







                                                                                                          share|improve this answer












                                                                                                          share|improve this answer



                                                                                                          share|improve this answer










                                                                                                          answered May 4 '16 at 15:04









                                                                                                          Konstantinos Chalkias

                                                                                                          3,32021521




                                                                                                          3,32021521























                                                                                                              13














                                                                                                              1.Hashmap and HashTable both store key and value.



                                                                                                              2.Hashmap can store one key as null. Hashtable can't store null.



                                                                                                              3.HashMap is not synchronized but Hashtable is synchronized.



                                                                                                              4.HashMap can be synchronized with Collection.SyncronizedMap(map)



                                                                                                              Map hashmap = new HashMap();

                                                                                                              Map map = Collections.SyncronizedMap(hashmap);





                                                                                                              share|improve this answer



















                                                                                                              • 1




                                                                                                                the 4th diff is nice, no one mentioned it, thanks
                                                                                                                – Rushabh Shah
                                                                                                                Aug 10 '15 at 4:06
















                                                                                                              13














                                                                                                              1.Hashmap and HashTable both store key and value.



                                                                                                              2.Hashmap can store one key as null. Hashtable can't store null.



                                                                                                              3.HashMap is not synchronized but Hashtable is synchronized.



                                                                                                              4.HashMap can be synchronized with Collection.SyncronizedMap(map)



                                                                                                              Map hashmap = new HashMap();

                                                                                                              Map map = Collections.SyncronizedMap(hashmap);





                                                                                                              share|improve this answer



















                                                                                                              • 1




                                                                                                                the 4th diff is nice, no one mentioned it, thanks
                                                                                                                – Rushabh Shah
                                                                                                                Aug 10 '15 at 4:06














                                                                                                              13












                                                                                                              13








                                                                                                              13






                                                                                                              1.Hashmap and HashTable both store key and value.



                                                                                                              2.Hashmap can store one key as null. Hashtable can't store null.



                                                                                                              3.HashMap is not synchronized but Hashtable is synchronized.



                                                                                                              4.HashMap can be synchronized with Collection.SyncronizedMap(map)



                                                                                                              Map hashmap = new HashMap();

                                                                                                              Map map = Collections.SyncronizedMap(hashmap);





                                                                                                              share|improve this answer














                                                                                                              1.Hashmap and HashTable both store key and value.



                                                                                                              2.Hashmap can store one key as null. Hashtable can't store null.



                                                                                                              3.HashMap is not synchronized but Hashtable is synchronized.



                                                                                                              4.HashMap can be synchronized with Collection.SyncronizedMap(map)



                                                                                                              Map hashmap = new HashMap();

                                                                                                              Map map = Collections.SyncronizedMap(hashmap);






                                                                                                              share|improve this answer














                                                                                                              share|improve this answer



                                                                                                              share|improve this answer








                                                                                                              edited Mar 22 '15 at 15:43









                                                                                                              Jared Burrows

                                                                                                              39.5k18121152




                                                                                                              39.5k18121152










                                                                                                              answered Aug 27 '14 at 11:29









                                                                                                              Rahul Tripathi

                                                                                                              2901515




                                                                                                              2901515








                                                                                                              • 1




                                                                                                                the 4th diff is nice, no one mentioned it, thanks
                                                                                                                – Rushabh Shah
                                                                                                                Aug 10 '15 at 4:06














                                                                                                              • 1




                                                                                                                the 4th diff is nice, no one mentioned it, thanks
                                                                                                                – Rushabh Shah
                                                                                                                Aug 10 '15 at 4:06








                                                                                                              1




                                                                                                              1




                                                                                                              the 4th diff is nice, no one mentioned it, thanks
                                                                                                              – Rushabh Shah
                                                                                                              Aug 10 '15 at 4:06




                                                                                                              the 4th diff is nice, no one mentioned it, thanks
                                                                                                              – Rushabh Shah
                                                                                                              Aug 10 '15 at 4:06











                                                                                                              11














                                                                                                              There are 5 basic differentiations with HashTable and HashMaps.




                                                                                                              1. Maps allows you to iterate and retrieve keys, values, and both key-value pairs as well, Where HashTable don't have all this capability.

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

                                                                                                              3. In hashmap you can remove element while iterating, safely. where as it is not possible in hashtables.

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

                                                                                                              5. HashTable won't allow null keys or null values. Where as HashMap allows one null key, and multiple null values.






                                                                                                              share|improve this answer




























                                                                                                                11














                                                                                                                There are 5 basic differentiations with HashTable and HashMaps.




                                                                                                                1. Maps allows you to iterate and retrieve keys, values, and both key-value pairs as well, Where HashTable don't have all this capability.

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

                                                                                                                3. In hashmap you can remove element while iterating, safely. where as it is not possible in hashtables.

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

                                                                                                                5. HashTable won't allow null keys or null values. Where as HashMap allows one null key, and multiple null values.






                                                                                                                share|improve this answer


























                                                                                                                  11












                                                                                                                  11








                                                                                                                  11






                                                                                                                  There are 5 basic differentiations with HashTable and HashMaps.




                                                                                                                  1. Maps allows you to iterate and retrieve keys, values, and both key-value pairs as well, Where HashTable don't have all this capability.

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

                                                                                                                  3. In hashmap you can remove element while iterating, safely. where as it is not possible in hashtables.

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

                                                                                                                  5. HashTable won't allow null keys or null values. Where as HashMap allows one null key, and multiple null values.






                                                                                                                  share|improve this answer














                                                                                                                  There are 5 basic differentiations with HashTable and HashMaps.




                                                                                                                  1. Maps allows you to iterate and retrieve keys, values, and both key-value pairs as well, Where HashTable don't have all this capability.

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

                                                                                                                  3. In hashmap you can remove element while iterating, safely. where as it is not possible in hashtables.

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

                                                                                                                  5. HashTable won't allow null keys or null values. Where as HashMap allows one null key, and multiple null values.







                                                                                                                  share|improve this answer














                                                                                                                  share|improve this answer



                                                                                                                  share|improve this answer








                                                                                                                  edited Apr 10 '14 at 15:44









                                                                                                                  Brad Larson

                                                                                                                  161k40363541




                                                                                                                  161k40363541










                                                                                                                  answered Dec 11 '13 at 12:45









                                                                                                                  user1923551

                                                                                                                  3,7762725




                                                                                                                  3,7762725























                                                                                                                      11














                                                                                                                      My small contribution :





                                                                                                                      1. First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe while Hashtable is a thread-safe collection.


                                                                                                                      2. Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable.


                                                                                                                      3. Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.








                                                                                                                      share|improve this answer




























                                                                                                                        11














                                                                                                                        My small contribution :





                                                                                                                        1. First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe while Hashtable is a thread-safe collection.


                                                                                                                        2. Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable.


                                                                                                                        3. Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.








                                                                                                                        share|improve this answer


























                                                                                                                          11












                                                                                                                          11








                                                                                                                          11






                                                                                                                          My small contribution :





                                                                                                                          1. First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe while Hashtable is a thread-safe collection.


                                                                                                                          2. Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable.


                                                                                                                          3. Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.








                                                                                                                          share|improve this answer














                                                                                                                          My small contribution :





                                                                                                                          1. First and most significant different between Hashtable and HashMap is that, HashMap is not thread-safe while Hashtable is a thread-safe collection.


                                                                                                                          2. Second important difference between Hashtable and HashMap is performance, since HashMap is not synchronized it perform better than Hashtable.


                                                                                                                          3. Third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.









                                                                                                                          share|improve this answer














                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer








                                                                                                                          edited Mar 22 '15 at 15:44









                                                                                                                          Jared Burrows

                                                                                                                          39.5k18121152




                                                                                                                          39.5k18121152










                                                                                                                          answered Mar 18 '14 at 21:46









                                                                                                                          Shreyos Adikari

                                                                                                                          7,922165573




                                                                                                                          7,922165573























                                                                                                                              8














                                                                                                                              HashTable is a legacy class in the jdk that shouldn't be used anymore. Replace usages of it with ConcurrentHashMap. If you don't require thread safety, use HashMap which isn't threadsafe but faster and uses less memory.






                                                                                                                              share|improve this answer























                                                                                                                              • Why are you repeating an already given answer?
                                                                                                                                – BalusC
                                                                                                                                Aug 6 '15 at 8:06










                                                                                                                              • Because I thought the other answers, at the time, didn't dismiss HashTable but explained that it was threadsafe. The truth is that as soon as you see HashTable in code, you should replace it with ConcurrentHashMap without skipping a beat. And if thread safety is not a concern then HashMap can be used to improve performance a bit.
                                                                                                                                – jontejj
                                                                                                                                Aug 7 '15 at 8:29
















                                                                                                                              8














                                                                                                                              HashTable is a legacy class in the jdk that shouldn't be used anymore. Replace usages of it with ConcurrentHashMap. If you don't require thread safety, use HashMap which isn't threadsafe but faster and uses less memory.






                                                                                                                              share|improve this answer























                                                                                                                              • Why are you repeating an already given answer?
                                                                                                                                – BalusC
                                                                                                                                Aug 6 '15 at 8:06










                                                                                                                              • Because I thought the other answers, at the time, didn't dismiss HashTable but explained that it was threadsafe. The truth is that as soon as you see HashTable in code, you should replace it with ConcurrentHashMap without skipping a beat. And if thread safety is not a concern then HashMap can be used to improve performance a bit.
                                                                                                                                – jontejj
                                                                                                                                Aug 7 '15 at 8:29














                                                                                                                              8












                                                                                                                              8








                                                                                                                              8






                                                                                                                              HashTable is a legacy class in the jdk that shouldn't be used anymore. Replace usages of it with ConcurrentHashMap. If you don't require thread safety, use HashMap which isn't threadsafe but faster and uses less memory.






                                                                                                                              share|improve this answer














                                                                                                                              HashTable is a legacy class in the jdk that shouldn't be used anymore. Replace usages of it with ConcurrentHashMap. If you don't require thread safety, use HashMap which isn't threadsafe but faster and uses less memory.







                                                                                                                              share|improve this answer














                                                                                                                              share|improve this answer



                                                                                                                              share|improve this answer








                                                                                                                              edited Apr 21 '13 at 17:27

























                                                                                                                              answered Apr 15 '13 at 14:49









                                                                                                                              jontejj

                                                                                                                              1,9921824




                                                                                                                              1,9921824












                                                                                                                              • Why are you repeating an already given answer?
                                                                                                                                – BalusC
                                                                                                                                Aug 6 '15 at 8:06










                                                                                                                              • Because I thought the other answers, at the time, didn't dismiss HashTable but explained that it was threadsafe. The truth is that as soon as you see HashTable in code, you should replace it with ConcurrentHashMap without skipping a beat. And if thread safety is not a concern then HashMap can be used to improve performance a bit.
                                                                                                                                – jontejj
                                                                                                                                Aug 7 '15 at 8:29


















                                                                                                                              • Why are you repeating an already given answer?
                                                                                                                                – BalusC
                                                                                                                                Aug 6 '15 at 8:06










                                                                                                                              • Because I thought the other answers, at the time, didn't dismiss HashTable but explained that it was threadsafe. The truth is that as soon as you see HashTable in code, you should replace it with ConcurrentHashMap without skipping a beat. And if thread safety is not a concern then HashMap can be used to improve performance a bit.
                                                                                                                                – jontejj
                                                                                                                                Aug 7 '15 at 8:29
















                                                                                                                              Why are you repeating an already given answer?
                                                                                                                              – BalusC
                                                                                                                              Aug 6 '15 at 8:06




                                                                                                                              Why are you repeating an already given answer?
                                                                                                                              – BalusC
                                                                                                                              Aug 6 '15 at 8:06












                                                                                                                              Because I thought the other answers, at the time, didn't dismiss HashTable but explained that it was threadsafe. The truth is that as soon as you see HashTable in code, you should replace it with ConcurrentHashMap without skipping a beat. And if thread safety is not a concern then HashMap can be used to improve performance a bit.
                                                                                                                              – jontejj
                                                                                                                              Aug 7 '15 at 8:29




                                                                                                                              Because I thought the other answers, at the time, didn't dismiss HashTable but explained that it was threadsafe. The truth is that as soon as you see HashTable in code, you should replace it with ConcurrentHashMap without skipping a beat. And if thread safety is not a concern then HashMap can be used to improve performance a bit.
                                                                                                                              – jontejj
                                                                                                                              Aug 7 '15 at 8:29











                                                                                                                              7














                                                                                                                              1)Hashtable is synchronized whereas hashmap is not.
                                                                                                                              2)Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.



                                                                                                                              3)HashMap permits null values in it, while Hashtable doesn't.






                                                                                                                              share|improve this answer

















                                                                                                                              • 3




                                                                                                                                HashMap iterator is fail-fast not fail-safe. Thats why we have ConcurrentHashMap that allows modification while iteration. Check this post journaldev.com/122/…
                                                                                                                                – Pankaj
                                                                                                                                Jan 28 '13 at 21:13






                                                                                                                              • 3




                                                                                                                                Why are you repeating an already given answer?
                                                                                                                                – BalusC
                                                                                                                                Aug 6 '15 at 8:02
















                                                                                                                              7














                                                                                                                              1)Hashtable is synchronized whereas hashmap is not.
                                                                                                                              2)Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.



                                                                                                                              3)HashMap permits null values in it, while Hashtable doesn't.






                                                                                                                              share|improve this answer

















                                                                                                                              • 3




                                                                                                                                HashMap iterator is fail-fast not fail-safe. Thats why we have ConcurrentHashMap that allows modification while iteration. Check this post journaldev.com/122/…
                                                                                                                                – Pankaj
                                                                                                                                Jan 28 '13 at 21:13






                                                                                                                              • 3




                                                                                                                                Why are you repeating an already given answer?
                                                                                                                                – BalusC
                                                                                                                                Aug 6 '15 at 8:02














                                                                                                                              7












                                                                                                                              7








                                                                                                                              7






                                                                                                                              1)Hashtable is synchronized whereas hashmap is not.
                                                                                                                              2)Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.



                                                                                                                              3)HashMap permits null values in it, while Hashtable doesn't.






                                                                                                                              share|improve this answer












                                                                                                                              1)Hashtable is synchronized whereas hashmap is not.
                                                                                                                              2)Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.



                                                                                                                              3)HashMap permits null values in it, while Hashtable doesn't.







                                                                                                                              share|improve this answer












                                                                                                                              share|improve this answer



                                                                                                                              share|improve this answer










                                                                                                                              answered Jan 22 '13 at 5:31









                                                                                                                              raja

                                                                                                                              1,96321721




                                                                                                                              1,96321721








                                                                                                                              • 3




                                                                                                                                HashMap iterator is fail-fast not fail-safe. Thats why we have ConcurrentHashMap that allows modification while iteration. Check this post journaldev.com/122/…
                                                                                                                                – Pankaj
                                                                                                                                Jan 28 '13 at 21:13






                                                                                                                              • 3




                                                                                                                                Why are you repeating an already given answer?
                                                                                                                                – BalusC
                                                                                                                                Aug 6 '15 at 8:02














                                                                                                                              • 3




                                                                                                                                HashMap iterator is fail-fast not fail-safe. Thats why we have ConcurrentHashMap that allows modification while iteration. Check this post journaldev.com/122/…
                                                                                                                                – Pankaj
                                                                                                                                Jan 28 '13 at 21:13






                                                                                                                              • 3




                                                                                                                                Why are you repeating an already given answer?
                                                                                                                                – BalusC
                                                                                                                                Aug 6 '15 at 8:02








                                                                                                                              3




                                                                                                                              3




                                                                                                                              HashMap iterator is fail-fast not fail-safe. Thats why we have ConcurrentHashMap that allows modification while iteration. Check this post journaldev.com/122/…
                                                                                                                              – Pankaj
                                                                                                                              Jan 28 '13 at 21:13




                                                                                                                              HashMap iterator is fail-fast not fail-safe. Thats why we have ConcurrentHashMap that allows modification while iteration. Check this post journaldev.com/122/…
                                                                                                                              – Pankaj
                                                                                                                              Jan 28 '13 at 21:13




                                                                                                                              3




                                                                                                                              3




                                                                                                                              Why are you repeating an already given answer?
                                                                                                                              – BalusC
                                                                                                                              Aug 6 '15 at 8:02




                                                                                                                              Why are you repeating an already given answer?
                                                                                                                              – BalusC
                                                                                                                              Aug 6 '15 at 8:02











                                                                                                                              6














                                                                                                                              Hashtable:



                                                                                                                              Hashtable 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 NullPointerException if you add null value. It is synchronized. So it comes with its cost. Only one thread can access HashTable at a particular time.



                                                                                                                              Example :



                                                                                                                              import java.util.Map;
                                                                                                                              import java.util.Hashtable;

                                                                                                                              public class TestClass {

                                                                                                                              public static void main(String args[ ]) {
                                                                                                                              Map<Integer,String> states= new Hashtable<Integer,String>();
                                                                                                                              states.put(1, "INDIA");
                                                                                                                              states.put(2, "USA");

                                                                                                                              states.put(3, null); //will throw NullPointerEcxeption at runtime

                                                                                                                              System.out.println(states.get(1));
                                                                                                                              System.out.println(states.get(2));
                                                                                                                              // System.out.println(states.get(3));

                                                                                                                              }
                                                                                                                              }


                                                                                                                              HashMap:



                                                                                                                              HashMap is like Hashtable but it also accepts key value pair. It allows null for both the keys and the values. Its performance better is better than HashTable, because it is unsynchronized.



                                                                                                                              Example:



                                                                                                                              import java.util.HashMap;
                                                                                                                              import java.util.Map;

                                                                                                                              public class TestClass {

                                                                                                                              public static void main(String args[ ]) {
                                                                                                                              Map<Integer,String> states = new HashMap<Integer,String>();
                                                                                                                              states.put(1, "INDIA");
                                                                                                                              states.put(2, "USA");

                                                                                                                              states.put(3, null); // Okay
                                                                                                                              states.put(null,"UK");

                                                                                                                              System.out.println(states.get(1));
                                                                                                                              System.out.println(states.get(2));
                                                                                                                              System.out.println(states.get(3));

                                                                                                                              }
                                                                                                                              }





                                                                                                                              share|improve this answer




























                                                                                                                                6














                                                                                                                                Hashtable:



                                                                                                                                Hashtable 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 NullPointerException if you add null value. It is synchronized. So it comes with its cost. Only one thread can access HashTable at a particular time.



                                                                                                                                Example :



                                                                                                                                import java.util.Map;
                                                                                                                                import java.util.Hashtable;

                                                                                                                                public class TestClass {

                                                                                                                                public static void main(String args[ ]) {
                                                                                                                                Map<Integer,String> states= new Hashtable<Integer,String>();
                                                                                                                                states.put(1, "INDIA");
                                                                                                                                states.put(2, "USA");

                                                                                                                                states.put(3, null); //will throw NullPointerEcxeption at runtime

                                                                                                                                System.out.println(states.get(1));
                                                                                                                                System.out.println(states.get(2));
                                                                                                                                // System.out.println(states.get(3));

                                                                                                                                }
                                                                                                                                }


                                                                                                                                HashMap:



                                                                                                                                HashMap is like Hashtable but it also accepts key value pair. It allows null for both the keys and the values. Its performance better is better than HashTable, because it is unsynchronized.



                                                                                                                                Example:



                                                                                                                                import java.util.HashMap;
                                                                                                                                import java.util.Map;

                                                                                                                                public class TestClass {

                                                                                                                                public static void main(String args[ ]) {
                                                                                                                                Map<Integer,String> states = new HashMap<Integer,String>();
                                                                                                                                states.put(1, "INDIA");
                                                                                                                                states.put(2, "USA");

                                                                                                                                states.put(3, null); // Okay
                                                                                                                                states.put(null,"UK");

                                                                                                                                System.out.println(states.get(1));
                                                                                                                                System.out.println(states.get(2));
                                                                                                                                System.out.println(states.get(3));

                                                                                                                                }
                                                                                                                                }





                                                                                                                                share|improve this answer


























                                                                                                                                  6












                                                                                                                                  6








                                                                                                                                  6






                                                                                                                                  Hashtable:



                                                                                                                                  Hashtable 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 NullPointerException if you add null value. It is synchronized. So it comes with its cost. Only one thread can access HashTable at a particular time.



                                                                                                                                  Example :



                                                                                                                                  import java.util.Map;
                                                                                                                                  import java.util.Hashtable;

                                                                                                                                  public class TestClass {

                                                                                                                                  public static void main(String args[ ]) {
                                                                                                                                  Map<Integer,String> states= new Hashtable<Integer,String>();
                                                                                                                                  states.put(1, "INDIA");
                                                                                                                                  states.put(2, "USA");

                                                                                                                                  states.put(3, null); //will throw NullPointerEcxeption at runtime

                                                                                                                                  System.out.println(states.get(1));
                                                                                                                                  System.out.println(states.get(2));
                                                                                                                                  // System.out.println(states.get(3));

                                                                                                                                  }
                                                                                                                                  }


                                                                                                                                  HashMap:



                                                                                                                                  HashMap is like Hashtable but it also accepts key value pair. It allows null for both the keys and the values. Its performance better is better than HashTable, because it is unsynchronized.



                                                                                                                                  Example:



                                                                                                                                  import java.util.HashMap;
                                                                                                                                  import java.util.Map;

                                                                                                                                  public class TestClass {

                                                                                                                                  public static void main(String args[ ]) {
                                                                                                                                  Map<Integer,String> states = new HashMap<Integer,String>();
                                                                                                                                  states.put(1, "INDIA");
                                                                                                                                  states.put(2, "USA");

                                                                                                                                  states.put(3, null); // Okay
                                                                                                                                  states.put(null,"UK");

                                                                                                                                  System.out.println(states.get(1));
                                                                                                                                  System.out.println(states.get(2));
                                                                                                                                  System.out.println(states.get(3));

                                                                                                                                  }
                                                                                                                                  }





                                                                                                                                  share|improve this answer














                                                                                                                                  Hashtable:



                                                                                                                                  Hashtable 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 NullPointerException if you add null value. It is synchronized. So it comes with its cost. Only one thread can access HashTable at a particular time.



                                                                                                                                  Example :



                                                                                                                                  import java.util.Map;
                                                                                                                                  import java.util.Hashtable;

                                                                                                                                  public class TestClass {

                                                                                                                                  public static void main(String args[ ]) {
                                                                                                                                  Map<Integer,String> states= new Hashtable<Integer,String>();
                                                                                                                                  states.put(1, "INDIA");
                                                                                                                                  states.put(2, "USA");

                                                                                                                                  states.put(3, null); //will throw NullPointerEcxeption at runtime

                                                                                                                                  System.out.println(states.get(1));
                                                                                                                                  System.out.println(states.get(2));
                                                                                                                                  // System.out.println(states.get(3));

                                                                                                                                  }
                                                                                                                                  }


                                                                                                                                  HashMap:



                                                                                                                                  HashMap is like Hashtable but it also accepts key value pair. It allows null for both the keys and the values. Its performance better is better than HashTable, because it is unsynchronized.



                                                                                                                                  Example:



                                                                                                                                  import java.util.HashMap;
                                                                                                                                  import java.util.Map;

                                                                                                                                  public class TestClass {

                                                                                                                                  public static void main(String args[ ]) {
                                                                                                                                  Map<Integer,String> states = new HashMap<Integer,String>();
                                                                                                                                  states.put(1, "INDIA");
                                                                                                                                  states.put(2, "USA");

                                                                                                                                  states.put(3, null); // Okay
                                                                                                                                  states.put(null,"UK");

                                                                                                                                  System.out.println(states.get(1));
                                                                                                                                  System.out.println(states.get(2));
                                                                                                                                  System.out.println(states.get(3));

                                                                                                                                  }
                                                                                                                                  }






                                                                                                                                  share|improve this answer














                                                                                                                                  share|improve this answer



                                                                                                                                  share|improve this answer








                                                                                                                                  edited Apr 26 '16 at 9:46









                                                                                                                                  manojgolty

                                                                                                                                  9217




                                                                                                                                  9217










                                                                                                                                  answered Feb 10 '15 at 7:44









                                                                                                                                  IntelliJ Amiya

                                                                                                                                  52.4k12111131




                                                                                                                                  52.4k12111131























                                                                                                                                      6














                                                                                                                                      HashMap and HashTable




                                                                                                                                      • Some important points about HashMap and HashTable.
                                                                                                                                        please read below details.


                                                                                                                                      1) Hashtable and Hashmap implement the java.util.Map interface
                                                                                                                                      2) Both Hashmap and Hashtable is the hash based collection. and working on hashing.
                                                                                                                                      so these are similarity of HashMap and HashTable.




                                                                                                                                      • What is the difference between HashMap and HashTable?


                                                                                                                                      1) First difference is HashMap is not thread safe While HashTable is ThreadSafe

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






                                                                                                                                      share|improve this answer



















                                                                                                                                      • 1




                                                                                                                                        Down-voted because this answer is not correct in some aspects. Hashtable does not implement the Map interface, but only extends the Dictionary class, which is obsolete.
                                                                                                                                        – Yannis Sermetziadis
                                                                                                                                        Oct 25 '17 at 5:42
















                                                                                                                                      6














                                                                                                                                      HashMap and HashTable




                                                                                                                                      • Some important points about HashMap and HashTable.
                                                                                                                                        please read below details.


                                                                                                                                      1) Hashtable and Hashmap implement the java.util.Map interface
                                                                                                                                      2) Both Hashmap and Hashtable is the hash based collection. and working on hashing.
                                                                                                                                      so these are similarity of HashMap and HashTable.




                                                                                                                                      • What is the difference between HashMap and HashTable?


                                                                                                                                      1) First difference is HashMap is not thread safe While HashTable is ThreadSafe

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






                                                                                                                                      share|improve this answer



















                                                                                                                                      • 1




                                                                                                                                        Down-voted because this answer is not correct in some aspects. Hashtable does not implement the Map interface, but only extends the Dictionary class, which is obsolete.
                                                                                                                                        – Yannis Sermetziadis
                                                                                                                                        Oct 25 '17 at 5:42














                                                                                                                                      6












                                                                                                                                      6








                                                                                                                                      6






                                                                                                                                      HashMap and HashTable




                                                                                                                                      • Some important points about HashMap and HashTable.
                                                                                                                                        please read below details.


                                                                                                                                      1) Hashtable and Hashmap implement the java.util.Map interface
                                                                                                                                      2) Both Hashmap and Hashtable is the hash based collection. and working on hashing.
                                                                                                                                      so these are similarity of HashMap and HashTable.




                                                                                                                                      • What is the difference between HashMap and HashTable?


                                                                                                                                      1) First difference is HashMap is not thread safe While HashTable is ThreadSafe

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






                                                                                                                                      share|improve this answer














                                                                                                                                      HashMap and HashTable




                                                                                                                                      • Some important points about HashMap and HashTable.
                                                                                                                                        please read below details.


                                                                                                                                      1) Hashtable and Hashmap implement the java.util.Map interface
                                                                                                                                      2) Both Hashmap and Hashtable is the hash based collection. and working on hashing.
                                                                                                                                      so these are similarity of HashMap and HashTable.




                                                                                                                                      • What is the difference between HashMap and HashTable?


                                                                                                                                      1) First difference is HashMap is not thread safe While HashTable is ThreadSafe

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







                                                                                                                                      share|improve this answer














                                                                                                                                      share|improve this answer



                                                                                                                                      share|improve this answer








                                                                                                                                      edited Jul 25 '17 at 14:59









                                                                                                                                      Pawan Patil

                                                                                                                                      508622




                                                                                                                                      508622










                                                                                                                                      answered Jul 5 '14 at 6:27









                                                                                                                                      JegsVala

                                                                                                                                      1,0701221




                                                                                                                                      1,0701221








                                                                                                                                      • 1




                                                                                                                                        Down-voted because this answer is not correct in some aspects. Hashtable does not implement the Map interface, but only extends the Dictionary class, which is obsolete.
                                                                                                                                        – Yannis Sermetziadis
                                                                                                                                        Oct 25 '17 at 5:42














                                                                                                                                      • 1




                                                                                                                                        Down-voted because this answer is not correct in some aspects. Hashtable does not implement the Map interface, but only extends the Dictionary class, which is obsolete.
                                                                                                                                        – Yannis Sermetziadis
                                                                                                                                        Oct 25 '17 at 5:42








                                                                                                                                      1




                                                                                                                                      1




                                                                                                                                      Down-voted because this answer is not correct in some aspects. Hashtable does not implement the Map interface, but only extends the Dictionary class, which is obsolete.
                                                                                                                                      – Yannis Sermetziadis
                                                                                                                                      Oct 25 '17 at 5:42




                                                                                                                                      Down-voted because this answer is not correct in some aspects. Hashtable does not implement the Map interface, but only extends the Dictionary class, which is obsolete.
                                                                                                                                      – Yannis Sermetziadis
                                                                                                                                      Oct 25 '17 at 5:42











                                                                                                                                      6














                                                                                                                                      HashMap: It is a class available inside java.util package and it is used to store the element in key and value format.



                                                                                                                                      Hashtable: It is a legacy class which is being recognized inside collection framework.






                                                                                                                                      share|improve this answer



















                                                                                                                                      • 4




                                                                                                                                        Why are you repeating an already given answer?
                                                                                                                                        – BalusC
                                                                                                                                        Aug 6 '15 at 8:02
















                                                                                                                                      6














                                                                                                                                      HashMap: It is a class available inside java.util package and it is used to store the element in key and value format.



                                                                                                                                      Hashtable: It is a legacy class which is being recognized inside collection framework.






                                                                                                                                      share|improve this answer



















                                                                                                                                      • 4




                                                                                                                                        Why are you repeating an already given answer?
                                                                                                                                        – BalusC
                                                                                                                                        Aug 6 '15 at 8:02














                                                                                                                                      6












                                                                                                                                      6








                                                                                                                                      6






                                                                                                                                      HashMap: It is a class available inside java.util package and it is used to store the element in key and value format.



                                                                                                                                      Hashtable: It is a legacy class which is being recognized inside collection framework.






                                                                                                                                      share|improve this answer














                                                                                                                                      HashMap: It is a class available inside java.util package and it is used to store the element in key and value format.



                                                                                                                                      Hashtable: It is a legacy class which is being recognized inside collection framework.







                                                                                                                                      share|improve this answer














                                                                                                                                      share|improve this answer



                                                                                                                                      share|improve this answer








                                                                                                                                      edited Dec 28 '18 at 2:05









                                                                                                                                      Pang

                                                                                                                                      6,8611563101




                                                                                                                                      6,8611563101










                                                                                                                                      answered Jan 31 '13 at 13:41









                                                                                                                                      Ankit

                                                                                                                                      12016




                                                                                                                                      12016








                                                                                                                                      • 4




                                                                                                                                        Why are you repeating an already given answer?
                                                                                                                                        – BalusC
                                                                                                                                        Aug 6 '15 at 8:02














                                                                                                                                      • 4




                                                                                                                                        Why are you repeating an already given answer?
                                                                                                                                        – BalusC
                                                                                                                                        Aug 6 '15 at 8:02








                                                                                                                                      4




                                                                                                                                      4




                                                                                                                                      Why are you repeating an already given answer?
                                                                                                                                      – BalusC
                                                                                                                                      Aug 6 '15 at 8:02




                                                                                                                                      Why are you repeating an already given answer?
                                                                                                                                      – BalusC
                                                                                                                                      Aug 6 '15 at 8:02











                                                                                                                                      4














                                                                                                                                      HashMaps gives you freedom of synchronization and debugging is lot more easier






                                                                                                                                      share|improve this answer

















                                                                                                                                      • 2




                                                                                                                                        Why are you repeating an already given answer?
                                                                                                                                        – BalusC
                                                                                                                                        Aug 6 '15 at 8:03






                                                                                                                                      • 2




                                                                                                                                        What does ~"freedom of synchronization" mean?
                                                                                                                                        – IgorGanapolsky
                                                                                                                                        Mar 24 '17 at 19:03
















                                                                                                                                      4














                                                                                                                                      HashMaps gives you freedom of synchronization and debugging is lot more easier






                                                                                                                                      share|improve this answer

















                                                                                                                                      • 2




                                                                                                                                        Why are you repeating an already given answer?
                                                                                                                                        – BalusC
                                                                                                                                        Aug 6 '15 at 8:03






                                                                                                                                      • 2




                                                                                                                                        What does ~"freedom of synchronization" mean?
                                                                                                                                        – IgorGanapolsky
                                                                                                                                        Mar 24 '17 at 19:03














                                                                                                                                      4












                                                                                                                                      4








                                                                                                                                      4






                                                                                                                                      HashMaps gives you freedom of synchronization and debugging is lot more easier






                                                                                                                                      share|improve this answer












                                                                                                                                      HashMaps gives you freedom of synchronization and debugging is lot more easier







                                                                                                                                      share|improve this answer












                                                                                                                                      share|improve this answer



                                                                                                                                      share|improve this answer










                                                                                                                                      answered Aug 9 '12 at 12:28







                                                                                                                                      user1506047















                                                                                                                                      • 2




                                                                                                                                        Why are you repeating an already given answer?
                                                                                                                                        – BalusC
                                                                                                                                        Aug 6 '15 at 8:03






                                                                                                                                      • 2




                                                                                                                                        What does ~"freedom of synchronization" mean?
                                                                                                                                        – IgorGanapolsky
                                                                                                                                        Mar 24 '17 at 19:03














                                                                                                                                      • 2




                                                                                                                                        Why are you repeating an already given answer?
                                                                                                                                        – BalusC
                                                                                                                                        Aug 6 '15 at 8:03






                                                                                                                                      • 2




                                                                                                                                        What does ~"freedom of synchronization" mean?
                                                                                                                                        – IgorGanapolsky
                                                                                                                                        Mar 24 '17 at 19:03








                                                                                                                                      2




                                                                                                                                      2




                                                                                                                                      Why are you repeating an already given answer?
                                                                                                                                      – BalusC
                                                                                                                                      Aug 6 '15 at 8:03




                                                                                                                                      Why are you repeating an already given answer?
                                                                                                                                      – BalusC
                                                                                                                                      Aug 6 '15 at 8:03




                                                                                                                                      2




                                                                                                                                      2




                                                                                                                                      What does ~"freedom of synchronization" mean?
                                                                                                                                      – IgorGanapolsky
                                                                                                                                      Mar 24 '17 at 19:03




                                                                                                                                      What does ~"freedom of synchronization" mean?
                                                                                                                                      – IgorGanapolsky
                                                                                                                                      Mar 24 '17 at 19:03











                                                                                                                                      4














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






                                                                                                                                      share|improve this answer





















                                                                                                                                      • Is that a comprehensive description of differences between the two apis?
                                                                                                                                        – IgorGanapolsky
                                                                                                                                        Mar 24 '17 at 19:04










                                                                                                                                      • Yes (sic!). That's all GWT developers need to know about it.
                                                                                                                                        – pong
                                                                                                                                        Mar 24 '17 at 19:41
















                                                                                                                                      4














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






                                                                                                                                      share|improve this answer





















                                                                                                                                      • Is that a comprehensive description of differences between the two apis?
                                                                                                                                        – IgorGanapolsky
                                                                                                                                        Mar 24 '17 at 19:04










                                                                                                                                      • Yes (sic!). That's all GWT developers need to know about it.
                                                                                                                                        – pong
                                                                                                                                        Mar 24 '17 at 19:41














                                                                                                                                      4












                                                                                                                                      4








                                                                                                                                      4






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






                                                                                                                                      share|improve this answer












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







                                                                                                                                      share|improve this answer












                                                                                                                                      share|improve this answer



                                                                                                                                      share|improve this answer










                                                                                                                                      answered Jul 15 '13 at 9:54









                                                                                                                                      pong

                                                                                                                                      454311




                                                                                                                                      454311












                                                                                                                                      • Is that a comprehensive description of differences between the two apis?
                                                                                                                                        – IgorGanapolsky
                                                                                                                                        Mar 24 '17 at 19:04










                                                                                                                                      • Yes (sic!). That's all GWT developers need to know about it.
                                                                                                                                        – pong
                                                                                                                                        Mar 24 '17 at 19:41


















                                                                                                                                      • Is that a comprehensive description of differences between the two apis?
                                                                                                                                        – IgorGanapolsky
                                                                                                                                        Mar 24 '17 at 19:04










                                                                                                                                      • Yes (sic!). That's all GWT developers need to know about it.
                                                                                                                                        – pong
                                                                                                                                        Mar 24 '17 at 19:41
















                                                                                                                                      Is that a comprehensive description of differences between the two apis?
                                                                                                                                      – IgorGanapolsky
                                                                                                                                      Mar 24 '17 at 19:04




                                                                                                                                      Is that a comprehensive description of differences between the two apis?
                                                                                                                                      – IgorGanapolsky
                                                                                                                                      Mar 24 '17 at 19:04












                                                                                                                                      Yes (sic!). That's all GWT developers need to know about it.
                                                                                                                                      – pong
                                                                                                                                      Mar 24 '17 at 19:41




                                                                                                                                      Yes (sic!). That's all GWT developers need to know about it.
                                                                                                                                      – pong
                                                                                                                                      Mar 24 '17 at 19:41











                                                                                                                                      4














                                                                                                                                      Synchronization or Thread Safe :



                                                                                                                                      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.



                                                                                                                                      Null keys and null values :



                                                                                                                                      HashMap allows one null key and any number of null values.Hashtable does not allow null keys or values.



                                                                                                                                      Iterating the values:



                                                                                                                                      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.



                                                                                                                                      Superclass and Legacy :



                                                                                                                                      HashMap is subclass of AbstractMap class whereas Hashtable is subclass of Dictionary class.



                                                                                                                                      Performance :



                                                                                                                                      As HashMap is not synchronized it is faster as compared to Hashtable.



                                                                                                                                      Refer http://modernpathshala.com/Article/1020/difference-between-hashmap-and-hashtable-in-java for examples and interview questions and quiz related to Java collection






                                                                                                                                      share|improve this answer




























                                                                                                                                        4














                                                                                                                                        Synchronization or Thread Safe :



                                                                                                                                        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.



                                                                                                                                        Null keys and null values :



                                                                                                                                        HashMap allows one null key and any number of null values.Hashtable does not allow null keys or values.



                                                                                                                                        Iterating the values:



                                                                                                                                        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.



                                                                                                                                        Superclass and Legacy :



                                                                                                                                        HashMap is subclass of AbstractMap class whereas Hashtable is subclass of Dictionary class.



                                                                                                                                        Performance :



                                                                                                                                        As HashMap is not synchronized it is faster as compared to Hashtable.



                                                                                                                                        Refer http://modernpathshala.com/Article/1020/difference-between-hashmap-and-hashtable-in-java for examples and interview questions and quiz related to Java collection






                                                                                                                                        share|improve this answer


























                                                                                                                                          4












                                                                                                                                          4








                                                                                                                                          4






                                                                                                                                          Synchronization or Thread Safe :



                                                                                                                                          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.



                                                                                                                                          Null keys and null values :



                                                                                                                                          HashMap allows one null key and any number of null values.Hashtable does not allow null keys or values.



                                                                                                                                          Iterating the values:



                                                                                                                                          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.



                                                                                                                                          Superclass and Legacy :



                                                                                                                                          HashMap is subclass of AbstractMap class whereas Hashtable is subclass of Dictionary class.



                                                                                                                                          Performance :



                                                                                                                                          As HashMap is not synchronized it is faster as compared to Hashtable.



                                                                                                                                          Refer http://modernpathshala.com/Article/1020/difference-between-hashmap-and-hashtable-in-java for examples and interview questions and quiz related to Java collection






                                                                                                                                          share|improve this answer














                                                                                                                                          Synchronization or Thread Safe :



                                                                                                                                          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.



                                                                                                                                          Null keys and null values :



                                                                                                                                          HashMap allows one null key and any number of null values.Hashtable does not allow null keys or values.



                                                                                                                                          Iterating the values:



                                                                                                                                          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.



                                                                                                                                          Superclass and Legacy :



                                                                                                                                          HashMap is subclass of AbstractMap class whereas Hashtable is subclass of Dictionary class.



                                                                                                                                          Performance :



                                                                                                                                          As HashMap is not synchronized it is faster as compared to Hashtable.



                                                                                                                                          Refer http://modernpathshala.com/Article/1020/difference-between-hashmap-and-hashtable-in-java for examples and interview questions and quiz related to Java collection







                                                                                                                                          share|improve this answer














                                                                                                                                          share|improve this answer



                                                                                                                                          share|improve this answer








                                                                                                                                          edited Apr 10 '16 at 4:46

























                                                                                                                                          answered Jan 5 '16 at 18:35









                                                                                                                                          amitguptageek

                                                                                                                                          444211




                                                                                                                                          444211






















                                                                                                                                              1 2
                                                                                                                                              next




                                                                                                                                              protected by Community Mar 16 '12 at 19:13



                                                                                                                                              Thank you for your interest in this question.
                                                                                                                                              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                                                                              Would you like to answer one of these unanswered questions instead?



                                                                                                                                              Popular posts from this blog

                                                                                                                                              Monofisismo

                                                                                                                                              compose and upload a new article using a custom form

                                                                                                                                              How to correct the classpath of spring boot application so that it contains a single, compatible version of...