In this post, we will learn the difference between HashMap and HashTable in Java. This is a frequently asked question in Java interviews for beginners. Let's dive into it.
Difference between HashMap and HashTable in Java
Features | HashMap | HashTable |
---|---|---|
Synchronization | Not synchronized (not thread-safe) | Internally synchronized (thread-safe) |
Null Elements | Allows one null key and any number of null values | Doesn't allow null keys and null values |
Iterators | Returns fail-fast iterators | Returns fail-safe Enumerations |
Class Extension | Extends AbstractMap class | Extends Dictionary class |
Traversal | Returns only iterator | Returns both Iterator and Enumeration |
Speed | Fast | Slow |
Legacy Class | Not a legacy class | Is a legacy class |
Preferred Use | Preferred in single-threaded applications; for multi-threaded, wrap using Collections.synchronizedMap() | Not preferred nowadays for multi-threaded applications; ConcurrentHashMap is a better option |
Example with HashMap:
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
// Create a HashMap
HashMap<Integer, String> hMap = new HashMap<>();
// Add elements (key-value pairs)
hMap.put(1, "apple");
hMap.put(2, "banana");
hMap.put(3, null);
hMap.put(null, "cherry");
// Display the HashMap
System.out.println("HashMap:");
for (Integer key : hMap.keySet()) {
System.out.println(key + " => " + hMap.get(key));
}
}
}
Output:
HashMap:
null => cherry
1 => apple
2 => banana
3 => null
Example with HashTable:
import java.util.Hashtable;
public class HashTableExample {
public static void main(String[] args) {
// Create a HashTable
Hashtable<Integer, String> hTable = new Hashtable<>();
// Add elements (key-value pairs)
hTable.put(1, "apple");
hTable.put(2, "banana");
hTable.put(3, "cherry");
// hTable.put(null, "date"); // This will throw NullPointerException
// hTable.put(4, null); // This will also throw NullPointerException
// Display the HashTable
System.out.println("HashTable:");
for (Integer key : hTable.keySet()) {
System.out.println(key + " => " + hTable.get(key));
}
}
}
Output:
HashTable:
1 => apple
2 => banana
3 => cherry
Download Cheat Sheet:
Related Collections Interview QA
- map() vs flatMap() in Java
- Collections vs Streams
- ArrayList vs Vector
- Iterator vs ListIterator
- HashMap vs HashTable
- HashSet vs HashMap
- Array vs ArrayList
- Fail-Fast Iterators vs Fail-Safe Iterators
- HashMap vs ConcurrentHashMap
- LinkedList vs ArrayDeque
- LinkedList vs Array
- LinkedList vs Doubly LinkedList
- Enum vs EnumSet in Java
- HashMap vs. TreeMap in Java
- Synchronized Collections vs. Concurrent Collections
Collection Framework
Interview Questions
Java
X vs Y
Comments
Post a Comment