Hashtable is a legacy collection class in Java that stores data in key–value pairs. It is part of java.util package and is synchronized by default, making it thread-safe.
null keys or valuesHashtable works internally using hash tables where keys are converted into hash codes. Based on the hash code, values are stored and retrieved efficiently.
// Importing Hashtable class
import java.util.Hashtable;
// Main class
public class HashtableDemo {
// Main method
public static void main(String[] args) {
// Creating Hashtable object
Hashtable<Integer, String> ht = new Hashtable<>();
// Adding elements to Hashtable
ht.put(1, "Java");
ht.put(2, "Python");
ht.put(3, "C++");
// Displaying Hashtable
System.out.println(ht);
}
}
{3=C++, 2=Python, 1=Java}
The output shows key–value pairs stored inside the Hashtable. Order is not guaranteed because hashing is used.
Simulate put(key, value) and remove(key)
HashMap or ConcurrentHashMap for modern applicationsremove()containsKey()