Both HashMap
and Hashtable
in Java are used to store key-value pairs, but there are some differences between them:
Synchronization:
Hashtable
is synchronized, which means it is thread-safe. Multiple threads can access aHashtable
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.
Null Values:
Hashtable
does not allow null keys or values. If you attempt to store a null key or value, it will throw aNullPointerException
.HashMap
allows one null key and multiple null values. You can store null values and a single null key in aHashMap
.
Performance:
HashMap
is generally faster due to not being synchronized. However, if synchronization is needed, you can useCollections.synchronizedMap(new HashMap<>())
to wrap a synchronized version of aHashMap
.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
Post a Comment