Sobes.tech
Junior

What is the difference between HashMap and Hashtable?

sobes.tech AI

Answer from AI

Main differences between HashMap and Hashtable in Java:

Feature HashMap Hashtable
Synchronization Not synchronized Synchronized
Thread safety No Yes
Null keys/values Allows one null key and multiple null values Neither null keys nor null values are allowed
Performance Higher (does not require locking) Lower (due to synchronization)
Inheritance Collection Framework (since Java 1.2) Older class (since Java 1.0), extends Dictionary
Iterators Fail-fast iterators (Iterator, ListIterator) Fail-safe iterator (Enumeration), also has Fail-fast iterators (Iterator)
// Example of using HashMap with null
Map<String, String> hashMap = new HashMap<>();
hashMap.put(null, "Value for null key");
hashMap.put("Key with null value", null);
System.out.println(hashMap); // Output: {null=Value for null key, Key with null value=null}

// Example of using Hashtable (adding null will cause an exception)
Map<String, String> hashtable = new Hashtable<>();
// hashtable.put(null, "Value for null key"); // Will throw NullPointerException
// hashtable.put("Key with null value", null); // Will throw NullPointerException

HashMap is preferred in most cases when thread safety is not explicitly required, due to better performance. Hashtable is used less frequently and mainly for compatibility with older code or when synchronization is necessary. In multithreaded environments, ConcurrentHashMap is typically used for thread-safe hash maps.