Java hashtable
Created By: chatGPT
Hashtable is a part of the Java Collection Framework and is used to store key-value pairs. It's similar to HashMap, but with the following differences: Hashtable is synchronized, which means it is thread-safe, while HashMap is not. Hashtable does not allow null keys or null values, whereas HashMap allows one null key and multiple null values. Here is a simple example of how to use a Hashtable in Java:
import java.util.Hashtable;
public class Example {
public static void main(String[] args) {
// Creating a Hashtable
Hashtable<String, Integer> hashtable = new Hashtable<>();
// Adding key-value pairs
hashtable.put("Apple", 1);
hashtable.put("Banana", 2);
hashtable.put("Cherry", 3);
// Retrieving a value
Integer value = hashtable.get("Apple");
System.out.println("Value for key 'Apple': " + value);
// Checking if a key exists
if (hashtable.containsKey("Banana")) {
System.out.println("Banana exists in the hashtable.");
}
// Displaying the size of the hashtable
System.out.println("Size of hashtable: " + hashtable.size());
// Iterating over keys
for (String key : hashtable.keySet()) {
System.out.println(key + " -> " + hashtable.get(key));
}
}
}
Important operations of a Hashtable include
put()
, get()
, remove()
, and size()
. You can also check if a key or value exists using containsKey()
and containsValue()
. Here are some methods demonstrated:hashtable.put("Date", 4); // Adding more elements
Integer removedValue = hashtable.remove("Cherry");
System.out.println("Removed value for key 'Cherry': " + removedValue);
boolean exists = hashtable.containsValue(2);
System.out.println("Does value 2 exist? " + exists);
When working with Hashtable, keep in mind that since it's synchronized, it can have performance overhead when multiple threads access it simultaneously. In scenarios where you expect high concurrency, consider using ConcurrentHashMap, which is also part of the Java Collections Framework and provides better performance in multithreaded environments.
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentExample {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put("One", 1);
concurrentMap.put("Two", 2);
System.out.println(concurrentMap.get("One")); // Output: 1
}
}