seperate chaining

PHOTO EMBED

Fri Jun 07 2024 14:01:40 GMT+0000 (Coordinated Universal Time)

Saved by @dbms

import java.util.LinkedList;

class KeyValuePair<K, V> {
    private K key;
    private V value;

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

    public K getKey() {
        return key;
    }

    public V getValue() {
        return value;
    }
}

class SeparateChaining<K, V> {
    private LinkedList<KeyValuePair<K, V>>[] table;
    private int capacity;
	
    @SuppressWarnings("unchecked")
    public SeparateChaining(int capacity) {
        this.capacity = capacity;
        this.table = new LinkedList[capacity];
        for (int i = 0; i < capacity; i++) {
            table[i] = new LinkedList<>();
        }
    }

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

    public void put(K key, V value) {
        int index = hash(key);
        LinkedList<KeyValuePair<K, V>> list = table[index];
        for (KeyValuePair<K, V> pair : list) {
            if (pair.getKey().equals(key)) {
                pair = new KeyValuePair<>(key, value);
                return;
            }
        }
        list.add(new KeyValuePair<>(key, value));
    }

    public V get(K key) {
        int index = hash(key);
        LinkedList<KeyValuePair<K, V>> list = table[index];
        for (KeyValuePair<K, V> pair : list) {
            if (pair.getKey().equals(key)) {
                return pair.getValue();
            }
        }
        return null;
    }

    public void remove(K key) {
        int index = hash(key);
        LinkedList<KeyValuePair<K, V>> list = table[index];
        for (KeyValuePair<K, V> pair : list) {
            if (pair.getKey().equals(key)) {
                list.remove(pair);
                return;
            }
        }
    }

    public void display() {
        for (int i = 0; i < capacity; i++) {
            System.out.print("Bucket " + i + ": ");
            for (KeyValuePair<K, V> pair : table[i]) {
                System.out.print("[" + pair.getKey() + ": " + pair.getValue() + "] ");
            }
            System.out.println();
        }
    }
}

public class SeparateChainingExample {
    public static void main(String[] args) {
        SeparateChaining<String, Integer> map = new SeparateChaining<>(5);

        map.put("John", 25);
        map.put("Alice", 30);
        map.put("Bob", 35);
        map.put("Doe", 40);  // Adding more elements to see separate chaining in action
        map.put("Eve", 45);

        System.out.println("Initial Map:");
        map.display();

        System.out.println("\nAlice's age: " + map.get("Alice"));
        System.out.println("Bob's age: " + map.get("Bob"));

        map.remove("Alice");

        System.out.println("\nMap after removing Alice:");
        map.display();

        System.out.println("Alice's age after removal: " + map.get("Alice"));
    }
}
content_copyCOPY