Java HashTable-interview
Q1. What is a Hashtable in Java?
A Hashtable is a legacy class in Java that implements a Map. It stores key–value pairs and is synchronized, meaning it is thread-safe. Keys and values cannot be null.
Q2. What are the key characteristics of Hashtable?
- Stores key-value pairs.
- No null key or null value is allowed.
- Synchronized (thread-safe but slower than HashMap).
- Belongs to the java.util package.
Q3. Difference between HashMap and Hashtable?
- HashMap → Allows one null key and multiple null values, not synchronized (faster).
- Hashtable → Does not allow null keys/values, synchronized (thread-safe but slower).
Q4. What are the main methods of Hashtable?
- put(key, value) → Adds a key-value pair.
- get(key) → Retrieves value by key.
- remove(key) → Removes mapping for a key.
- containsKey(key) / contains(value) → Checks existence.
- keys() / elements() → Returns Enumeration of keys/values.
Q5. When should you use Hashtable over HashMap?
Use Hashtable when thread safety is required without needing external synchronization. For non-thread-safe applications, HashMap is preferred for performance.