Kuidas erinevad HashMap ja Hashtable kogumikud nende rakendamise viiside ja omaduste poolest?
sobes.tech AI
Vastus AI-lt
HashMap and Hashtable are implementations of the Map interface in Java, but they have some differences:
-
Synchronization: Hashtable is synchronized (thread-safe), which makes it slower in a multithreaded environment. HashMap is not synchronized, so it is faster but not safe for multithreaded access without external synchronization.
-
Null allowance: HashMap allows one null key and multiple null values. Hashtable does not allow null keys or null values.
-
Inheritance: Hashtable is an older class, inheriting from Dictionary, while HashMap inherits from AbstractMap.
-
Usage: In modern applications, it is preferable to use HashMap, and if synchronization is needed, use ConcurrentHashMap or external synchronization of HashMap.
Example of using HashMap:
Map<String, Integer> map = new HashMap<>();
map.put("key", 1);
Integer value = map.get("key");