Skip to main content
Published on

Hashtable Class in Java

Share:

Introduction

The Hashtable is one of the first data structures provided by Java, present since its very first version. Its ability to store key-value pairs makes it indispensable for many applications that require efficient data storage and retrieval.

Hashtable Class Features

  1. Synchronized: Unlike HashMap, the Hashtable is thread-safe, meaning multiple threads can share a single Hashtable without the need for additional synchronisation.
  2. Does not allow null values: In the Hashtable, you cannot have null keys or values, which is a significant difference compared to other data structures such as HashMap.
  3. Efficiency: Using a hashing technique, Hashtables guarantee near-constant access times, making value retrieval extremely fast.
  4. Capacity and Load Factor: The Hashtable has a constructor that accepts both the initial capacity and the load factor. This allows you to optimise the table in terms of size and efficiency.

Main Methods

In addition to the basic insertion and retrieval methods, the Hashtable offers a variety of useful methods:

  • clear(): Clears the table.
  • contains(): Checks whether a value is present.
  • containsKey(): Checks for the presence of a specific key.
  • containsValue(): Similar to contains(), but clearer in its intent.
  • get(): Retrieves a value based on the provided key.
  • isEmpty(): Checks whether the table is empty.
  • keys(): Returns an enumeration of the keys in the table.
  • size(): Returns the number of key-value pairs in the table.
package com.caffeinealgorithm.programaremjava;

import java.util.Hashtable;

public class HashtableClass {
  private Hashtable<String, Integer> people = new Hashtable<>();

  public void Run() {
    people.put("Nelson Silva", 28);
    people.put("Larissa Fernandes", 37);
    people.put("Pedro Henrique", 52);
    people.put("Raquel Soares", 68);

    people.replace("Pedro Henrique", 100);
    people.remove("Larissa Fernandes");
    // people.clear();

    System.out.printf("People's names: %s\n", people.keySet());
    System.out.printf("People's ages: %s", people.values());
  }
}

/*
  People's names: [Nelson Silva, Raquel Soares, Pedro Henrique]
  People's ages: [28, 68, 100]
*/

Applicability

Given its synchronised nature, the Hashtable is ideal for applications where multiple threads may try to access and modify data simultaneously. It is also frequently used in applications that require high query rates and low insertion/update rates.

Conclusion

Mastering the Hashtable class and its nuances is fundamental for Java developers. This data structure has stood the test of time and remains relevant in many programming scenarios. Investing time in understanding how it works and its characteristics can translate into more efficient and robust code in your applications.

Happy coding!