What are the differences between a HashMap and a Hashtable in Java?

 

Both HashMap and Hashtable in Java are used to store key-value pairs, but there are some differences between them:

  1. Synchronization:

    • Hashtable is synchronized, which means it is thread-safe. Multiple threads can access a Hashtable concurrently without causing data corruption.
    • HashMap is not synchronized by default. If you need thread safety, you need to explicitly synchronize access using external synchronization methods.
  2. Null Values:

    • Hashtable does not allow null keys or values. If you attempt to store a null key or value, it will throw a NullPointerException.
    • HashMap allows one null key and multiple null values. You can store null values and a single null key in a HashMap.
  3. Performance:

    • HashMap is generally faster due to not being synchronized. However, if synchronization is needed, you can use Collections.synchronizedMap(new HashMap<>()) to wrap a synchronized version of a HashMap.
    • Hashtable is slower due to synchronization.

Here's a comparison using examples:

HashMap Example:

java
import java.util.HashMap; import java.util.Map; public class HashMapExample { public static void main(String[] args) { Map<Integer, String> hashMap = new HashMap<>(); hashMap.put(1, "One"); hashMap.put(2, "Two"); hashMap.put(3, "Three"); System.out.println("HashMap: " + hashMap); } }

Hashtable Example:

java
import java.util.Hashtable; import java.util.Map; public class HashtableExample { public static void main(String[] args) { Hashtable<Integer, String> hashtable = new Hashtable<>(); hashtable.put(1, "One"); hashtable.put(2, "Two"); hashtable.put(3, "Three"); System.out.println("Hashtable: " + hashtable); } }

In both examples, we create instances of HashMap and Hashtable and store key-value pairs. The basic usage is similar, but keep in mind the synchronization and null handling differences when choosing between them. If you don't require thread safety, HashMap is generally preferred due to its better performance.

Comments