109 lines
2.9 KiB
Java
109 lines
2.9 KiB
Java
package net.abhinavsarkar.algorist;
|
|
|
|
import java.util.Optional;
|
|
|
|
public class ChainingHashTable<K, V>
|
|
{
|
|
private Object[] store;
|
|
|
|
public ChainingHashTable(int capacity) {
|
|
if (capacity <= 0) {
|
|
throw new IllegalArgumentException("Capacity too small");
|
|
}
|
|
this.store = new Object[capacity];
|
|
}
|
|
|
|
public Optional<V> get(K key) {
|
|
int index = calcIndex(key);
|
|
|
|
LinkedList<Entry<K, V>> entries = (LinkedList<Entry<K, V>>) 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<Entry<K, V>> vNode = new LinkedList.Node<>(new Entry<>(key, val), null);
|
|
if (store[index] == null) {
|
|
store[index] = new LinkedList<>(vNode);
|
|
} else {
|
|
LinkedList<Entry<K, V>> entries = (LinkedList<Entry<K, V>>) store[index];
|
|
Optional<Integer> 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<K, V> {
|
|
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<Entry<K, V>> entries = (LinkedList<Entry<K, V>>) 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<String, String> 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);
|
|
}
|
|
|
|
}
|