Differences between HashMap and Hash-table
Java provides different types of Map implementations, two of the most commonly used being HashMap and Hashtable. Both of these classes implement the Map< interface and store key-value pairs, but they differ significantly in terms of synchronization, performance, and usage. In this article, we will explore the differences in detail.
Introduction
A Map in Java is a collection of key-value pairs where each key is unique. Both HashMap and Hashtable use a hashing mechanism to store and retrieve data efficiently. However, they have different characteristics that make them suitable for different use cases.
Key Differences Between HashMap and Hashtable
The table below provides a summary of the key differences between HashMap and Hashtable:
Feature | HashMap | Hashtable |
---|---|---|
Synchronization | Not synchronized (not thread-safe) | Synchronized (thread-safe) |
Performance | Faster (no overhead of synchronization) | Slower (due to synchronization) |
Null Keys/Values | Allows one null key and multiple null values | Does not allow null keys or values |
Iteration | Uses Iterator (fail-fast) | Uses Enumerator (legacy, not fail-safe) |
Inheritance | Extends AbstractMap | Extends Dictionary (legacy class) |
Thread Safety | Requires external synchronization for multi-threading | Thread-safe, but may impact performance |
Use Case | Best for non-threaded applications | Suitable for multi-threaded environments |
- Synchronization or Thread Safe : One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap cannot be shared between multiple threads without proper synchronization. Java 5 introduced ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
- Null keys and null values : The HashMap class is roughly equivalent to Hashtable, except that it
permits nulls. (HashMap permits one null key and multiple null values.
Hashtable doesn't permit any sort of nulls (key or values).).
- Iterating the values: The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. This is also an important difference between Enumeration and Iterator in Java.
- Default Capacity:
- Hashmap: static final int DEFAULT_INITIAL_CAPACITY =16 static final float DEFAULT_LOAD_FACTOR = 0.75f;
- Hashtable: static final int DEFAULT_INITIAL_CAPACITY = 11; static final float DEFAULT_LOAD_FACTOR = 0.75f;
- HashMap does not guarantee that the order of the map will remain constant over time.
Here is example of a C program that uses a for loop to calculate the sum of 'n' numbers:
- import java.util.HashMap;
- import java.util.Hashtable;
- public class HashMapHashtableExample {
- public static void main(String[] args) {
- Hashtable<String,String> hashtableobj = new Hashtable<String, String>();
- hashtableobj.put("name", "ramu");
- hashtableobj.put("petname", "ram");
- System.out.println("Hashtable object output :"+ hashtableobj);
- HashMap hashmapobj = new HashMap();
- hashmapobj.put("name", "ramu");
- hashmapobj.put("pertname", "ram");
- System.out.println("HashMap object output :"+hashmapobj);
- }
- }
HashMap in Java
What is HashMap?
HashMap<K, V> is a part of the java.util package and implements the Map<K, V> interface. It stores key-value pairs using a hashing mechanism, which allows efficient insertion, deletion, and retrieval operations.
Characteristics of HashMap
Not synchronized: Multiple threads can access a HashMap concurrently, but this can lead to inconsistent data if modifications occur.
Allows null values and a single null key.
Unordered: Does not guarantee any specific order of keys.
Performance: Fast for most operations since there is no synchronization overhead.
Hashtable in Java
What is Hashtable?
Hashtable<K, V> is a legacy class from Java 1.0 that implements the Map<K, V> interface and extends the Dictionary<K, V> class. It stores key-value pairs using hashing and provides built-in synchronization, making it thread-safe.
Characteristics of Hashtable
Synchronized: All methods are thread-safe but can lead to performance bottlenecks.
Does not allow null keys or values.
Unordered: Similar to HashMap, it does not guarantee the order of keys.
Uses Enumerator instead of Iterator (legacy mechanism, should be avoided).