Difference Between HashMap VS Hashtable Java With Example

HashMap VS Hashtable In Java: In this article, we will discuss the difference between HashMap and Hashtable Java classes in detail i.e.; HashMap vs Hashtable

Hashtable is legacy class and based on hashcode of keys where keys are unique and it is exactly the same as HashMap with few differences with respect to following points

  • Synchronized methods
  • Performance
  • Null key insertion
  • Null value insertion

Lets us move on and discuss the key differences between these 2 Map implemented classes

HashMap vs Hashtable

HashMap
Hashtable
HashMap is introduced in collection framework in Java 1.2 versionHashtable is a legacy class and introduced in Java 1.0 version
HashMap is NOT synchronizedHashtable is synchronized
All methods of HashMap is NOT synchronized i.e.; it is not thread-safeAll methods of HashMap is synchronized i.e.; thread-safe
Multiple threads are allowed to accessOnly one thread is allowed access; other threads have to wait to get access, after obtaining lock/monitor
Performance-wise, this is relatively high comparing with Hashtable, as there is no wait timePerformance-wise, this is relatively slow due to synchronized methods as there is only one thread allowed to access, at any given point of time
NULL insertion allowed for both keys and valuesNULL insertion is not allowed for both keys and values
Maximum of one NULL key and there is no upper limit for valuesSimply, not allowed for both keys & values

Note: both use the hash table data structure to store key-value pairs

When to use HashMap?

  • HashMap stores key-value pairs which use a hashing technique to store key-value pairs where methods are NOT synchronized
  • So, the search operation is faster with multiple threads access
  • So, if the business requirement is to store key-value pairs for faster search operation or number of search operation on the basis of keys; without concerning concurrent access to the map
  • Then, HashMap is the very apt choice

When to use Java Hashtable?

  • This is exactly the same as that of HashMap, but every method is synchronized
  • Performance-wise is relatively slower than comparing HashMap
  • So, if the business requirement is to store key-value pairs for faster search operation with synchronized access
  • Then, Java Hashtable is the preferred choice over HashMap

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment