Differences between Hashmap and Hashtable

Differences between Hashmap and Hashtable

FeatureHashMapHashtable
SynchronizationNot synchronized (non-thread-safe)Synchronized (thread-safe)
Null Keys and ValuesAllows null keys and multiple null valuesDoesn’t allow null keys or values (throws NullPointerException)
PerformanceGenerally faster due to lack of synchronizationSlower due to synchronization overhead
Introduced VersionIntroduced in Java 1.2Introduced in Java 1.0
Legacy StatusNon-legacy (modern)Legacy (older)

 Hashmap and Hashtable

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.

Homepage

Readmore