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 Class

  1. HashTable is a legacy class of Java introduced in JDK 1.0
  2. It implements the collection framework. It was re-engineered again in Java 2 to implement the Map interface also.
  3. It doesn’t allow any Null value. One can not store Null as a key or a value.
  4. When it comes to performance, HashTables have low key performance.
  5. HashTable extends the Dictionary class.
  6. Traversing of elements in a HashTable can be done by both iterators or enumerators.
  7. 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.
  8. HashTable is Synchronized which means only one thread can modify the HashTable at a Time.

HashMap Class

  1. HashMap was introduced and added in JDK 1.2
  2. It implements Map and Serializable interface.
  3. 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.
  4. HashMaps are faster than HashTables.
  5. It extends the AbstractMap class.
  6. Traversing of elements in a HashMap can be done by iterators only.
  7. 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.
  8. 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!”

Leave a Reply

Your email address will not be published. Required fields are marked *