Difference between Hashmap and Hashtable, HashMap Vs HashTable, HashMap Realtime Example, HashTable Realtime Example, Difference between HashMap and Hashtable with Example, HashTable Vs HashMap, Difference HashMap and HashTable with Realtime Examples.
HashMap Vs HashTable ? Is it Possible to make HashMap synchronized ?
HashTable Vs HashMap
In Java Collection Frame work Difference between HashMap and HashTable is one most Frequently Asked question in Java interview for Freshers,2+,3+,5+,6+ Experience also. Candidate’s who are going to attend for the Interview must be perfect in Core java and Collection Frame Work. In this Collection Frame Work we explained the Difference HashMap and HashTable is most often asked in the Interview, So Candidate must be Prefect in this Sections.
Difference Between HashMap and Hashtable in Java
Hashtable and HashMap both of them implements Map Interface, But there are some difference between them, that helps to decide whether to Hashtable or HashMap in Java.
1) HashMap is Similar to Hashtable, but its not Sychronized and allows null values. HashMap represented as key value pair in which both Key, Value allows null value.
2) One of the main Difference between HashMap and Hashtable, HashMap is not synchronized whereas Hashtable is synchronized. Hashtable is thread safe and hashtable is not threadsafe(allows multiple threads to share a resource or object).
3) From Java 5 Version introduces the ConcurrentHashMap which is an alternative for HashMap and has better performance than Hashtable in java.
4) Another Major Significant Difference is Iterator in HashMap is fail and fast safe iterator, While enumerator is used for retrieving the data in thread safe manner, that throws ConcurrentModificationException, when any another is trying to modify the data in map.
5) Another final Difference between Hashtable and HashMap in which due to thread safe and synchronization Hashtable is very slow compare to HashMap because of single threaded approach.
Description for New Terms
1) Sychronization is process that allows one thread to access the Hashtable, It means first of all it holds the lock on the object of Hashtable while any thread is going to access the Hashtable.
2) Another Term is Fail-safe is related to Iterators. If an Iterator or ListIterator is created on the Collection Object. If any thread tries to modify the that Collection Object then it throws ConcurrentModfificationException.
HashMap Sychronization Using Collections Method
In Java Collection HashMap Can be Sychronized by using Collections sychronizedMap(HashMap) method.
3) HashMap can be Sychronized by using Collections Class Method (i.e) synchronizedMap(HashMap).
Ex: Map m=Collections.synchronizedMap(HashMap);