// Hash Table with open addressing // uses String keys, and the java String method hashCode() import java.util.*; interface Map { public int size(); public boolean isEmpty(); public Object get(String k); public void put(String k, Object v); public void remove(String k); } class Pair { public String key; public Object value; Pair(String k, Object v) { key = k; value = v; } } class HashTable implements Map { int size; int capacity; Pair bucket[]; HashTable() { this(1000); } HashTable(int cap) { capacity = cap; bucket = new Pair[cap]; size = 0; for (int i = 0; i < cap; i++) bucket[i] = null; } public int size() { return size; } public boolean isEmpty() { return size == 0; } public Object get(String k){ int i = locate(k); if (i == -1) return null; return bucket[i].value; } public void remove(String k) { int i = locate(k); if (i == -1) return; bucket[i].key = null; } public void put(String k, Object v) { int i = locate(k); if (i != -1) bucket[i].value = v; else { i = findSpace(k); if (i != -1) bucket[i] = new Pair(k, v); } } // hashing and collision resolution by linear probing private int locate(String k) { int h = k.hashCode() % capacity; int step = 0; while (step < capacity) { int index = resolve(h, step); if (bucket[index] == null) return -1; if (k.equals(bucket[index].key)) return index; step++; } return -1; } private int findSpace(String k) { int h = k.hashCode() % capacity; int step = 0; while (step < capacity) { int index = resolve(h, step); if (bucket[index] == null) return index; if (bucket[index].key == null) return index; step++; } return -1; } // linear probing resolution private int resolve(int h, int step) { return (h + step) % capacity; } public void dump() { for (int i = 0; i < capacity; i++) { if (bucket[i] != null && bucket[i].key != null) { System.out.println("" + i + ": " + bucket[i].key + " " + bucket[i].value); } } } public static void main(String args[]) { Map m = new HashTable(16); testMap(m); } public static void testMap(Map m) { boolean done = false; while (!done) { try { Scanner sc = new Scanner(System.in); System.out.println("\ncmds are + - D F Q: >>"); String cmd = sc.next(); String key = null; String value = null; char command = cmd.charAt(0); if (command != 'Q' && command != 'D') key = sc.next(); if (command == '+') value = sc.next(); else value = null; switch (cmd.charAt(0)) { case 'Q': done = true; value = null; break; case 'D': ((HashTable) m).dump(); break; case '+': m.put(key, value); break; case '-': m.remove(key); break; case 'F': value = (String) m.get(key); break; } if (value != null) System.out.println("Value: " + value); } catch (Exception e) { System.out.println("Error " + e.toString()); } } } }