Comparison between HashMap and Hashtable is a common question in Java interviews, which is used to test whether programmers can use collection classes correctly and whether they can adapt to various ideas to solve problems. How HashMap works, comparison of ArrayList with Vector, and this question is the most classic question about Java collection frameworks. Hashtable is an outdated collection class that has existed in the Java API for a long time. It was rewritten in Java 4 and implemented the Map interface, so it has since become part of the Java collection framework. Hashtable and HashMap are quite easy to ask in Java interviews, and have even become the most common questions to be tested in collection framework interviews, so don't forget to prepare this question before participating in any Java interviews.
In this article, we will not only see the difference between HashMap and Hashtable, but also the similarities between them.
The difference between HashMap and Hashtable
Both HashMap and Hashtable implement Map interfaces, but before deciding which one to use, you must first figure out the difference between them. The main differences are: thread safety, synchronization, and speed.
Some important terms to note:
1) sychronized means that only one thread can change the Hashtable at a time. That is to say, any thread must first obtain the synchronization lock when it wants to update the Hashtable. Other threads must wait until the synchronization lock is released before they can obtain the synchronization lock and update the Hashtable again.
2) Fail-safe and iterator iterator are related. If a collection object creates an Iterator or ListIterator, and then other threads try to change the collection object "structurally", a ConcurrentModificationException exception will be thrown. But other threads can change the collection object through the set() method is allowed because this does not change the collection "structurally". However, if the structure has been changed and the set() method is called, an IllegalArgumentException exception will be thrown.
3) Structural changes refer to deleting or inserting an element, which will affect the structure of the map.
Can we make HashMap sync?
HashMap can be synchronized through the following statement:
Map m = Collections.synchronizeMap(hashMap);
in conclusion
There are several main differences between Hashtable and HashMap: thread safety and speed. Use Hashtable only when you need complete thread safety, and if you use Java 5 or above, please use ConcurrentHashMap.
Original link: Javarevisited Translation: ImportNew.com - Tang Xiaojuan Translation Link: http://www.importnew.com/7010.html