Hashtable in Java
Hashtable in Java is a class that stores key-value pairs in a hash table, much like HashMap. It is used to look up values by key. Unlike HashMap, every method of Hashtable is synchronized, and it allows no null keys and no null values. Hashtable has existed since Java 1.0 and is a legacy class; in Java 1.2 it was updated to implement Map. In this lesson, you will learn how Hashtable works and what modern code uses instead.
Declaration
public class Hashtable<K, V> extends Dictionary<K, V>
implements Map<K, V>, Cloneable, SerializableDictionary is an even older abstract class, now obsolete.
Features of Hashtable
- Key-value pairs with unique keys.
- Synchronized: only one thread can use it at a time.
- No
null: anullkey or value throwsNullPointerException. - No guaranteed order.
- Default capacity 11, load factor 0.75; it grows to
2 x old + 1. - Legacy methods:
elements()andkeys()return anEnumeration.
Example: Using Hashtable
Let's see an example of the main operations and the null rule.
import java.util.Enumeration;
import java.util.Hashtable;
public class HashtableDemo {
public static void main(String[] args) {
Hashtable<String, Integer> marks = new Hashtable<>();
marks.put("Navika", 91);
marks.put("Srihitha", 78);
marks.put("Advitha", 85);
System.out.println("Navika: " + marks.get("Navika"));
System.out.println("Size: " + marks.size());
Enumeration<String> keys = marks.keys();
int count = 0;
while (keys.hasMoreElements()) {
keys.nextElement();
count++;
}
System.out.println("Keys seen: " + count);
try {
marks.put("Anamaneni", null);
} catch (NullPointerException e) {
System.out.println("null value rejected");
}
}
}Navika: 91
Size: 3
Keys seen: 3
null value rejectedExplanation: put and get work exactly as in a HashMap. keys() returns an old-style Enumeration. Trying to store a null value throws NullPointerException, which a HashMap would have accepted.
Why Hashtable Is Not Used Today
- Slow: every call takes a lock on the whole table, even in single-threaded code.
- Poor concurrency: with many threads, only one can read or write at a time.
- Better options exist:
HashMapfor one thread, andConcurrentHashMapfor many threads, which lets many threads read and write at once.
Common Mistakes
Storing null values. Hashtable throws; HashMap allows them.
Choosing Hashtable for thread safety in new code. ConcurrentHashMap is faster and safer for compound updates through merge and compute.
Practice
- Easy: Rewrite the example with
HashMapand a for-each loop overentrySet(). - Harder: Write a method that copies a
Hashtableinto aTreeMapand prints it in sorted key order.
Key Takeaways
Was this tutorial helpful?