Sobes.tech
Junior — Middle

What distinguishes the data structure HashTable from HashMap and what are their main differences?

sobes.tech AI

Answer from AI

HashTable and HashMap are data structures for storing key-value pairs with fast access by key, but they have several important differences:

  • Thread safety: HashTable is synchronized (thread-safe), meaning it supports safe access from multiple threads without additional synchronization. HashMap is not synchronized, so external synchronization is required when accessed by multiple threads.

  • Support for null: HashMap allows null as a key and value. HashTable does not permit null as a key or value.

  • Performance: HashMap is generally faster because it does not have the overhead of synchronization.

  • Inheritance: HashMap is part of Java Collections with generics (since Java 1.2), HashTable is an older implementation.

Example of using HashMap:

Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
Integer count = map.get("apple");

If thread safety is needed, it is better to use ConcurrentHashMap instead of HashTable.

What distinguishes the data structure HashTable from… - sobes.tech