Hashtable in Java

Hashtable is a collection in Java that is used to store and manage key/value pairs. It is similar to HashMap, but it is synchronized and therefore thread-safe. It implements the Map interface, which means that it uses the key/value pair to store data. Hashtable stores data in an array, and it is a hash table data structure.

Features of Hashtable in Java

  1. Synchronization: Hashtable is synchronized, which means that it can be accessed by multiple threads simultaneously. This makes it thread-safe and suitable for use in multi-threaded environments.

  2. No null keys or values: Hashtable does not allow null keys or values. If you try to add null keys or values, it will throw a NullPointerException.

  3. Capacity: Hashtable has a capacity that specifies the number of key/value pairs that it can store. When the capacity is exceeded, it automatically increases its size to accommodate more data.

  4. Load Factor: Hashtable has a load factor that specifies the maximum percentage of the hash table that can be filled before it is resized. The default load factor is 0.75.

  5. Enumeration: Hashtable provides an Enumeration interface that can be used to iterate over the keys and values in the Hashtable.

Let's see an example of Hashtable in Java.

import java.util.Hashtable;
import java.util.Map;
public class HashtableExample {
  public static void main(String[] args) {
    // Create a Hashtable object
    Hashtable<String, String> ht = new Hashtable<String, String>();
    // Add key/value pairs to the Hashtable
    ht.put("key1", "value1");
    ht.put("key2", "value2");
    ht.put("key3", "value3");
    // Print the Hashtable
    System.out.println("Hashtable: " + ht);
    // Get a value from the Hashtable using a key
    String value = ht.get("key2");
    System.out.println("Value of key2: " + value);
    // Remove a key/value pair from the Hashtable
    ht.remove("key3");
    System.out.println("Hashtable after removing key3: " + ht);
    // Iterate over the Hashtable using an Enumeration
    System.out.println("Iterating over Hashtable:");
    Enumeration<String> keys = ht.keys();
    while (keys.hasMoreElements()) {
      String key = keys.nextElement();
      String val = ht.get(key);
      System.out.println(key + " = " + val);
    }
  }
}​​

Output:

Hashtable: {key3=value3, key2=value2, key1=value1}
Value of key2: value2
Hashtable after removing key3: {key2=value2, key1=value1}
Iterating over Hashtable:
key2 = value2
key1 = value1

In the above example, we have created a Hashtable object and added some key/value pairs to it using the put() method. We have then printed the Hashtable using the println() method. We have retrieved the value of a key using the get() method and removed a key/value pair using the remove() method. Finally, we have iterated over the Hashtable using an Enumeration object.