Hashtable in Java

A Hashtable in Java is a data structure that stores key-value pairs, similar to a map. It is implemented using a hash table, which is a data structure that uses a hash function to map keys to indexes in an array. This allows for fast insertion and retrieval of elements, with an average time complexity of O(1) for most operations.

Hashtable is thread-safe

One of the main advantages of a Hashtable is that it is thread-safe, which means that multiple threads can access and modify the table simultaneously without the need for external synchronization. This makes it useful for building concurrent applications.

However, a Hashtable is not as efficient as some other map implementations, such as HashMap, in terms of performance. It is also not suitable for use with mutable keys, as the key’s hash code may change after it has been added to the table, leading to unpredictable behavior.

Here is an example of how to create and use a Hashtable in Java:

import java.util.Hashtable;

public class Main {
  public static void main(String[] args) {
    // Create a Hashtable with default capacity and load factor
    Hashtable<String, Integer> table = new Hashtable<>();

    // Add some key-value pairs to the table
    table.put("Radha", 25);
    table.put("Krishnan", 30);
    table.put("Hari", 35);

    // Check if the table contains a key
    if (table.containsKey("Radha")) {
      System.out.println("Radha is in the table");

    // Get the value for a key
    int age = table.get("Hari");
    System.out.println("Hari is " + age + " years old");

    // Remove a key-value pair from the table

In this example, we create a Hashtable with String keys and Integer values, and add some key-value pairs to it. We then use the containsKey method to check if a key is in the table, and the get method to retrieve the value for a key. Finally, we use the remove method to remove a key-value pair from the table.