Differences between Hashmap and Hashtable
Feature | HashMap | Hashtable |
Synchronization | Not synchronized (non-thread-safe) | Synchronized (thread-safe) |
Null Keys and Values | Allows null keys and multiple null values | Doesn’t allow null keys or values (throws NullPointerException) |
Performance | Generally faster due to lack of synchronization | Slower due to synchronization overhead |
Introduced Version | Introduced in Java 1.2 | Introduced in Java 1.0 |
Legacy Status | Non-legacy (modern) | Legacy (older) |

Table of Contents
Now, let’s illustrate these differences with examples:
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class HashMapVsHashtable {
public static void main(String[] args) {
// Example using HashMap
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(100, "Amit");
hashMap.put(104, "Amit");
hashMap.put(101, "Vijay");
hashMap.put(102, "Rahul");
System.out.println("-----------HashMap-----------");
for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
// Example using Hashtable
Hashtable<Integer, String> hashtable = new Hashtable<>();
hashtable.put(101, "ajay");
hashtable.put(101, "Vijay");
hashtable.put(102, "Ravi");
hashtable.put(103, "Rahul");
System.out.println("-------------Hashtable--------------");
for (Map.Entry<Integer, String> entry : hashtable.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
Output:
———–HashMap———–
100 Amit
101 Vijay
102 Rahul
104 Amit
————-Hashtable————–
101 Vijay
102 Ravi
103 Rahul
Remember that HashMap is preferred for non-threaded applications, while Hashtable is thread-safe but less performant due to synchronization.