Basic Hash Table Implementation in 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.

Leave a Reply

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