package net.abhinavsarkar.algorist; import java.util.Optional; public class ChainingHashTable { private Object[] store; public ChainingHashTable(int capacity) { if (capacity <= 0) { throw new IllegalArgumentException("Capacity too small"); } this.store = new Object[capacity]; } public Optional get(K key) { int index = calcIndex(key); LinkedList> entries = (LinkedList>) store[index]; if (entries == null) { return Optional.empty(); } else { return entries.forEach(h -> { if (h.key.equals(key)) { return Optional.of(h.val); } return Optional.empty(); }); } } public void put(K key, V val) { int index = calcIndex(key); LinkedList.Node> vNode = new LinkedList.Node<>(new Entry<>(key, val), null); if (store[index] == null) { store[index] = new LinkedList<>(vNode); } else { LinkedList> entries = (LinkedList>) store[index]; Optional ret = entries.forEach(h -> { if (h.key.equals(key)) { h.val = val; return Optional.of(0); } return Optional.empty(); }); if (!ret.isPresent()) { entries.prepend(vNode); } } } private int calcIndex(K key) { return key.hashCode() % store.length; } private static class Entry { private K key; private V val; public Entry(K key, V val) { this.key = key; this.val = val; } public String toString() { return "<" + key + "," + val + ">"; } } public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < store.length; i++) { LinkedList> entries = (LinkedList>) store[i]; if (entries != null) { sb.append("<" + i + ": " + entries + ">, "); } } sb.delete(sb.length()-2, sb.length()); return "{" + sb + "}"; } public static void main(String[] args) { ChainingHashTable table = new ChainingHashTable<>(20); table.put("a", "abhinav"); table.put("b", "batman"); table.put("c", "carol"); table.put("c", "carly"); table.put("z", "zellman"); table.put("w", "walker"); System.out.println(table.get("a")); System.out.println(table.get("b")); System.out.println(table.get("c")); System.out.println(table.get("A")); System.out.println(table.get("B")); System.out.println(table.get("C")); System.out.println(table); } }