Java Hashtable Class
Hashtable belongs to the Java Collections Framework and is defined within the java.util package. It is a key-value pair data structure like HashMap, but with one major difference: Hashtable is synchronized, meaning it is thread-safe.
Key Features
- Stores key-value pairs
- Thread-safe (synchronized)
- The Hashtable data structure prevents the usage of both null keys and null values.
- Slower than HashMap due to synchronization
- Preserves no order
Syntax
Hashtable<KeyType, ValueType> table = new Hashtable<>();
Example
Hashtable<Integer, String> students = new Hashtable<>();
Example
import java.util.Hashtable;
import java.util.Map;
public class HashtableExample {
public static void main(String[] args) {
Hashtable<Integer, String> employees = new Hashtable<>();
// Adding key-value pairs
employees.put(100, "Alice");
employees.put(101, "Bob");
employees.put(102, "Charlie");
// Display all entries
for (Map.Entry<Integer, String> entry : employees.entrySet()) {
System.out.println("ID: " + entry.getKey() + ", Name: " + entry.getValue());
}
// Update and remove
employees.put(101, "Bobby");
employees.remove(100);
// Check contains
System.out.println("Has key 102? " + employees.containsKey(102));
System.out.println("Has value 'Charlie'? " + employees.containsValue("Charlie"));
// Size
System.out.println("Size: " + employees.size());
}
}
Note
- Hashtable should be employed exclusively for legacy systems where thread safety is essential.
- For modern thread-safe applications, prefer ConcurrentHashMap.
- Slower performance than HashMap due to synchronization.
- The Java Collections Framework initially did not include this component which was incorporated afterward.
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com