Differences between HashMap and hashtable


Both HashMap and hashtable implement the map interface, but before deciding which one to use, we must find out the differences between them. The main differences are: thread safety, synchronization, and speed.

HashMap is almost equivalent to hashtable, except that HashMap is non synchronized and can accept null (HashMap can accept null key and value, while hashtable cannot).

HashMap is not synchronized, while hashtable is synchronized, which means that hashtable is thread safe and multiple threads can share a hashtable; Without proper synchronization, multiple threads cannot share HashMap. Java 5 provides concurrenthashmap, which is an alternative to hashtable and has better scalability than hashtable.Big data training

Another difference is that the iterator of HashMap is a fail fast iterator, while the enumerator iterator of hashtable is not a fail fast iterator. Therefore, when other threads change the structure of the HashMap (add or remove elements), they will throw a concurrentmodificationexception, but the remove () method of the iterator itself will not throw a concurrentmodificationexception. But this is not an inevitable behavior, depending on the JVM. This is also the difference between enumeration and iterator.

Because hashtable is thread safe and synchronized, it is slower than HashMap in a single threaded environment. If you don’t need synchronization and only need a single thread, the performance of HashMap is better than hashtable.

HashMap cannot guarantee that the order of elements in the map will remain unchanged over time.

Some important terms to note:

Synchronized means that only one thread can change the hashtable at a time. That is, when any thread wants to update the hashtable, it must first obtain the synchronization lock. Other threads cannot obtain the synchronization lock again until the synchronization lock is released to update the hashtable.

Fail safe is related to iterator iterators. If a collection object creates an iterator or listiterator, and other threads try to “structurally” change the collection object, they will throw a concurrentmodificationexception. However, it is allowed that other threads can change the collection object through the set () method, because this does not change the collection “structurally”. However, if you call the set () method after a structural change has been made, an illegalargumentexception will be thrown.

Structural changes refer to the deletion or insertion of an element, which will affect the structure of the map.

Can we synchronize HashMap?

HashMap can be synchronized through the following statement:

Map m = Collections.synchronizeMap(hashMap);

Hashtable and HashMap have several main differences: thread safety and speed. Use hashtable only when you need full thread safety. If you use Java 5 or above, please use concurrent HashMap.