Junior — Middle
Explain the differences between HashMap and Hashtable classes and when to prefer each.
sobes.tech AI
Answer from AI
HashMap and Hashtable are implementations of the Map interface in Java, but there are key differences:
-
Synchronization: Hashtable is synchronized (thread-safe), which makes it slower in single-threaded applications. HashMap is not synchronized, so it is faster but not safe for concurrent access without external synchronization.
-
Support for null: HashMap allows one null key and multiple null values. Hashtable does not permit null keys or null values.
-
Inheritance: Hashtable is a legacy class, inherited from Dictionary, while HashMap inherits from AbstractMap.
When to use:
- If thread safety without additional synchronization is needed, you can use Hashtable, but modern alternatives like ConcurrentHashMap are preferred.
- For most cases, especially in single-threaded applications, HashMap is preferable due to better performance and flexibility.
Example of using HashMap:
Map<String, Integer> map = new HashMap<>();
map.put(null, 1); // allowed
map.put("key", 2);