Difference between HashMap and HashTable in Java
Hello Learners, today we are going to learn about the difference between HashMap and HashTable in Java. HashMap and Hashtable both store data in a key and value pair. Both the classes internally use hashing technique to store the unique key values. Both the classes use hash table internally to store the elements. Let’s see the differences in points to get you a basic idea of how they are different from each other.
- HashTable is a legacy class of Java introduced in JDK 1.0
- It implements the collection framework. It was re-engineered again in Java 2 to implement the Map interface also.
- It doesn’t allow any Null value. One can not store Null as a key or a value.
- When it comes to performance, HashTables have low key performance.
- HashTable extends the Dictionary class.
- Traversing of elements in a HashTable can be done by both iterators or enumerators.
- The enumerator used with HashTable is not fail-safe in nature. If the HashTable is modified during traversing then it will not throw any error.
- HashTable is Synchronized which means only one thread can modify the HashTable at a Time.
- HashMap was introduced and added in JDK 1.2
- It implements Map and Serializable interface.
- It allows Null values but with some restrictions. You can add only 1 key as Null as all the keys must be unique. but you can add multiple null values.
- HashMaps are faster than HashTables.
- It extends the AbstractMap class.
- Traversing of elements in a HashMap can be done by iterators only.
- The iterators used with HashMap are fail-fast in nature. If you try to modify the HashMap while traversing then it will throw an error immediately.
- HashMap is not Synchronized and it can be modified by multiple threads at a given time. But we can synchronize the HashMap explicitly by using synchronizedMap method.
Make a HashMap synchronized --> Map map = Collections.synchronizedMap(hashmap);
NOTE: HashTable has a method contains() along with that creates confusion if you have a value added as a key and value both. So, HashMap doesn’t have this method and only uses ContainsValue() and ContainsKey() method. These methods return true if certain key or value is found in the HashMap.
HashMap is generally preferred more over HashTables because of performance. Synchronization isn’t a problem because we can make it synchronized anyways explicitly.
You can learn more about iterators and enumerators
So, that’s all for now about the difference between HashMap and HashTable in Java. Till then Keep Learning, Keep Practicing, Keep Reading.
“THINK TWICE CODE ONCE!”