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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.