Introduction
The Java Hashtable class is one of the oldest implementations of the Map interface in the Java Collections Framework. It stores data as key-value pairs, where each key is unique and maps to a single value. Although it has been available since the early versions of Java, Hashtable is still used in some legacy applications that require thread-safe access to shared data.
The Hashtable class belongs to the java.util package and internally uses a hash table to store entries. It is synchronized, which means multiple threads can safely access and modify the Hashtable without causing data inconsistency. However, because of synchronization, Hashtable is generally slower than HashMap.
Java Hashtable does not allow null keys or null values. Attempting to insert either a null key or a null value will result in a NullPointerException.
What is Java Hashtable?
A Hashtable is a collection that stores data in the form of key-value pairs.
- Each key must be unique.
- Duplicate values are allowed.
- Keys and values cannot be null.
- All public methods are synchronized, making Hashtable thread-safe.
Example:
| Key | Value |
|---|---|
| 101 | Rahul |
| 102 | Amit |
| 103 | Neha |
Here:
- Keys: 101, 102, 103
- Values: Rahul, Amit, Neha
You can quickly retrieve a value using its key.
Java Hashtable Hierarchy
Object
│
Dictionary
│
Hashtable
The Hashtable class implements the following interfaces:
- Map
- Cloneable
- Serializable
Unlike HashMap, Hashtable extends the legacy Dictionary class.
Features of Java Hashtable
Some important features of Hashtable are:
- Stores data as key-value pairs
- Keys must be unique
- Allows duplicate values
- Does not allow null keys
- Does not allow null values
- Thread-safe because methods are synchronized
- Uses a hash table internally
- Dynamic size
- Supports Generics
- Suitable for legacy synchronized applications
Syntax
Import Statement
import java.util.Hashtable;
or
import java.util.*;
Creating a Hashtable
Hashtable<Integer, String> students = new Hashtable<>();
Using the Map interface:
Map<Integer, String> students = new Hashtable<>();
Using the interface improves flexibility and follows Java best practices.
Constructors of Hashtable
1. Default Constructor
Hashtable<Integer, String> table = new Hashtable<>();
Creates an empty Hashtable with the default initial capacity and load factor.
2. Constructor with Initial Capacity
Hashtable<Integer, String> table = new Hashtable<>(20);
Creates a Hashtable with an initial capacity of 20.
3. Constructor with Capacity and Load Factor
Hashtable<Integer, String> table = new Hashtable<>(20,0.75f);
Creates a Hashtable with:
- Initial Capacity = 20
- Load Factor = 0.75
4. Constructor from Another Map
Map<Integer, String> Map = new HashMap<>();
map.put(101, "Rahul");
map.put(102, "Amit");
Hashtable<Integer, String> table = new Hashtable<>(map);
System.out.println(table);
Output
Common Methods of Hashtable
| Method | Description |
|---|---|
| put() | Adds or updates a key-value pair |
| get() | Retrieves the value associated with a key |
| remove() | Removes a key-value pair |
| containsKey() | Checks if a key exists |
| containsValue() | Checks if a value exists |
| keySet() | Returns all keys |
| values() | Returns all values |
| entrySet() | Returns all key-value pairs |
| size() | Returns the number of entries |
| isEmpty() | Checks whether the Hashtable is empty |
| clear() | Removes all entries |
Example 1: Creating a Hashtable
import java.util.*;
public class HashtableExample {
public static void main(String[] args) {
Hashtable<Integer, String> students = new Hashtable<>();
students.put(101, "Rahul");
students.put(102, "Amit");
students.put(103, "Neha");
System.out.println(students);
}
}
Output
The iteration order is not guaranteed.
Example 2: Retrieving a Value
import java.util.*;
public class GetExample {
public static void main(String[] args) {
Hashtable<Integer, String> students = new Hashtable<>();
students.put(101, "Rahul");
System.out.println(students.get(101));
}
}
Output
Example 3: Updating a Value
import java.util.*;
public class UpdateExample {
public static void main(String[] args) {
Hashtable<Integer, String> students = new Hashtable<>()
students.put(101, "Rahul");
students.put(101, "Rohan");
System.out.println(students);
}
}
Output
Duplicate keys replace the previous value.
Example 4: Removing an Entry
import java.util.*;
public class RemoveExample {
public static void main(String[] args) {
Hashtable<Integer, String> students = new Hashtable<>()
students.put(101, "Rahul");
students.put(102, "Amit");
students.remove(102);
System.out.println(students);
}
}
Output
Example 5: Iterating Through Hashtable
import java.util.*;
public class LoopExample {
public static void main(String[] args) {
Hashtable<Integer, String> students = new Hashtable<>()
students.put(101, "Rahul");
students.put(102, "Amit");
students.put(103, "Neha");
for (Map.Entry entry : students.entrySet()) {
System.out.println(entry.getKey()
+ " : "
+ entry.getValue());
}
}
}
Output
102 : Amit
103 : Neha
How Hashtable Works Internally
Hashtable internally uses a hash table to store entries.
The process is:
- The hashCode() method of the key is called.
- The hash code determines the bucket where the entry is stored.
- If multiple keys map to the same bucket, collision handling is applied.
- Every public method is synchronized, allowing only one thread to execute it at a time.
Because of synchronization, Hashtable is safe for multi-threaded use but slower than HashMap.
Hashtable vs HashMap vs ConcurrentHashMap
| Feature | Hashtable | HashMap | ConcurrentHashMap |
|---|---|---|---|
| Thread-safe | Yes | No | Yes |
| Null Key | No | Yes | No |
| Null Values | No | Yes | No |
| Performance | Moderate | Fastest | High |
| Synchronization | Entire methods | None | Fine-grained locking |
| Introduced | Java 1.0 | Java 1.2 | Java 5 |
Time Complexity
| Operation | Time Complexity |
|---|---|
| put() | O(1) |
| get() | O(1) |
| remove() | O(1) |
| containsKey() | O(1) |
| containsValue() | O(1) |
Although the average complexity is O(1), synchronization adds overhead.
Real-life Example
Imagine you’re developing a legacy banking application where multiple threads update customer information simultaneously.
Hashtable<Integer, String> accounts = new Hashtable<>()
accounts.put(1001, "Savings");
accounts.put(1002, "Current");
accounts.put(1003, "Fixed Deposit");
Since Hashtable is synchronized, concurrent updates from multiple threads are handled safely.
Other real-world applications include:
- Legacy enterprise applications
- Banking systems
- Multi-threaded desktop applications
- Shared configuration storage
- Older servlet-based applications
- Network management software
- Financial record systems
- Government information systems
Advantages of Java Hashtable
- Thread-safe implementation
- Fast average lookup time
- Dynamic resizing
- Prevents duplicate keys
- Supports Generics
- Reliable for legacy applications
- Easy to use
- Well-tested over many Java versions
Limitations of Java Hashtable
- Slower than HashMap due to synchronization
- Does not allow null keys
- Does not allow null values
- Does not maintain insertion order
- Considered a legacy class
- Less scalable than ConcurrentHashMap in highly concurrent applications
Common Mistakes
1. Adding a Null Key
Incorrect:
Hashtable<Integer, String> tables = new Hashtable<>()
table.put(null, "Java");
This throws a NullPointerException.
2. Adding a Null Value
Incorrect:
table.put(101, null);
This also throws a NullPointerException.
3. Assuming Hashtable Maintains Order
table.put(3, "C");
table.put(1, "A");
table.put(2, "B");
Hashtable does not preserve insertion order or sort keys.
4. Forgetting Generics
Incorrect:
Hashtable table = new Hashtable();
Correct:
Hashtable<Integer, String> tables = new Hashtable<>()
5. Using Hashtable in New High-Concurrency Applications
For modern concurrent applications, prefer ConcurrentHashMap because it provides better scalability and performance.
Best Practices
- Declare variables using the Map interface.
Hashtable<Integer, String> students = new Hashtable<>()
- Use Hashtable only when working with legacy APIs or when specifically required.
- Use HashMap for single-threaded applications.
- Use ConcurrentHashMap for modern multi-threaded applications.
- Always use Generics for type safety.
- Never insert null keys or null values.
Conclusion
The Java Hashtable class is a legacy, thread-safe implementation of the Map interface that stores data as key-value pairs using a hash table. It provides fast average lookup performance while ensuring thread safety through synchronized methods.
Although modern Java applications typically use HashMap or ConcurrentHashMap, understanding Hashtable remains valuable because it is still found in older codebases and is a common topic in Java interviews.