Java
Java

 

 

This document provides a simple implementation of a hash table in Java. A hash table is a data structure that offers a way to efficiently store and retrieve data using key-value pairs.

Program Structure

The hash table is implemented using an array of linked lists. Each index in the array represents a bucket that can hold multiple entries in case of hash collisions. The main operations implemented are:

  • Put: Insert a key-value pair into the hash table.
  • Get: Retrieve a value associated with a specific key.
  • Remove: Delete a key-value pair from the hash table.

Java Code


import java.util.LinkedList;

class HashTable<K, V> {
    private static class Entry<K, V> {
        K key;
        V value;

        Entry(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }

    private LinkedList<Entry<K, V>>[] table;
    private int size;

    @SuppressWarnings("unchecked")
    public HashTable(int capacity) {
        table = new LinkedList[capacity];
        for (int i = 0; i < capacity; i++) {
            table[i] = new LinkedList<>();
        }
        size = 0;
    }

    private int hash(K key) {
        return Math.abs(key.hashCode() % table.length);
    }

    public void put(K key, V value) {
        int index = hash(key);
        LinkedList<Entry<K, V>> bucket = table[index];

        for (Entry<K, V> entry : bucket) {
            if (entry.key.equals(key)) {
                entry.value = value; // Update existing key
                return;
            }
        }

        bucket.add(new Entry<>(key, value));
        size++;
    }

    public V get(K key) {
        int index = hash(key);
        LinkedList<Entry<K, V>> bucket = table[index];

        for (Entry<K, V> entry : bucket) {
            if (entry.key.equals(key)) {
                return entry.value; // Return the found value
            }
        }

        return null; // Return null if key not found
    }

    public void remove(K key) {
        int index = hash(key);
        LinkedList<Entry<K, V>> bucket = table[index];

        bucket.removeIf(entry -> entry.key.equals(key));
        size--;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }
}

// Example usage
public class Main {
    public static void main(String[] args) {
        HashTable<String, Integer> hashTable = new HashTable<>(10);
        hashTable.put("apple", 1);
        hashTable.put("banana", 2);
        hashTable.put("orange", 3);

        System.out.println("Value for 'apple': " + hashTable.get("apple"));
        hashTable.remove("banana");
        System.out.println("Value for 'banana': " + hashTable.get("banana"));
        System.out.println("Current size: " + hashTable.size());
    }
}

Documentation

Class: HashTable

The HashTable class implements a hash table with basic functionalities.

Constructor

  • HashTable(int capacity): Initializes a hash table with a specified capacity.

Methods

  • void put(K key, V value): Inserts a key-value pair into the hash table.
  • V get(K key): Retrieves the value associated with the specified key.
  • void remove(K key): Removes the key-value pair associated with the specified key.
  • int size(): Returns the number of entries in the hash table.
  • boolean isEmpty(): Checks if the hash table is empty.

Example Usage

The example usage demonstrates how to create a hash table, insert values, retrieve a value, and remove an entry.

 

Explanation of the Code

  1. Class Structure:
    • The HashTable class has a nested Entry class that holds key-value pairs.
    • An array of LinkedList<Entry<K, V>> is used to manage buckets for collision handling.
  2. Methods:
    • hash(K key): Computes the index for a given key using the modulo operator on the hash code.
    • put(K key, V value): Inserts a new key-value pair or updates the value if the key already exists.
    • get(K key): Retrieves the value associated with a key.
    • remove(K key): Deletes the entry associated with the specified key.
    • size() and isEmpty() provide information about the hash table’s current state.

This implementation is a straightforward way to demonstrate how hash tables work while also handling collisions efficiently with linked lists.

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)