Home page

Sunday, June 18, 2023

Hashtable in JAVA

In Java, a HashTable is a data structure that maps keys to values. It is part of the Java Collections Framework and is similar to a HashMap. The HashTable class is thread-safe and is synchronized, which means it can be used in multi-threaded environments where thread safety is required.

The purpose of using a HashTable is to store and retrieve key-value pairs efficiently. It provides constant-time complexity for basic operations like get and put (assuming a good hash function and minimal collisions). Some common use cases for HashTable include:

Storing and retrieving data: If you need to store data with a unique key and be able to retrieve it quickly using that key, a HashTable can be used. The key can be any object, and the value can be associated with it.

Ensuring thread safety: If you are working in a multi-threaded environment and need a thread-safe data structure, HashTable can be used. It guarantees thread safety by using synchronization.

Here's an example of how you can use a HashTable in Java:

import java.util.Hashtable;

public class HashTableExample {

    public static void main(String[] args) {

        // Create a HashTable

        Hashtable<String, Integer> scores = new Hashtable<>();

        // Add key-value pairs to the HashTable

        scores.put("John", 90);

        scores.put("Alice", 85);

        scores.put("Bob", 95);

        // Retrieve values from the HashTable

        int johnScore = scores.get("John");

        System.out.println("John's score: " + johnScore);

        // Check if a key exists in the HashTable

        boolean containsAlice = scores.containsKey("Alice");

        System.out.println("Contains Alice? " + containsAlice);

        // Remove a key-value pair from the HashTable

        scores.remove("Bob");

        // Size of the HashTable

        int size = scores.size();

        System.out.println("Size of HashTable: " + size);

    }

}

In this example, we create a Hashtable called scores that maps String keys to Integer values.

We add key-value pairs to the HashTable using the put() method.

We retrieve values from the HashTable using the get() method and store them in variables.

We check if a key exists in the HashTable using the containsKey() method.

We remove a key-value pair from the HashTable using the remove() method.

Finally, we get the size of the HashTable using the size() method.

Output:

John's score: 90

Contains Alice? true

Size of HashTable: 2

As shown in the example, HashTable provides a way to store key-value pairs and retrieve values efficiently. It ensures thread safety but can have performance implications due to synchronization. If thread safety is not a requirement, it is generally recommended to use HashMap instead. 

No comments:

Post a Comment