82 lines
1.8 KiB
Java
82 lines
1.8 KiB
Java
package net.abhinavsarkar.algorist.hash;
|
|
|
|
import java.util.Iterator;
|
|
import java.util.Optional;
|
|
import net.abhinavsarkar.algorist.Map;
|
|
|
|
public class LRWCache<K, V> implements Iterable<K>
|
|
{
|
|
|
|
private final int capacity;
|
|
private final OpenAddressingHashTable<K, V> store;
|
|
|
|
public LRWCache(int capacity) {
|
|
this.capacity = capacity;
|
|
this.store = new OpenAddressingHashTable<>(capacity+1);
|
|
}
|
|
|
|
public Optional<V> get(K key) {
|
|
return store.get(key);
|
|
}
|
|
|
|
public void remove(K key) {
|
|
store.remove(key);
|
|
}
|
|
|
|
public void put(K key, V val) {
|
|
store.put(key, val);
|
|
if (store.size() > capacity) {
|
|
store.remove(store.iterator().next().getKey());
|
|
}
|
|
}
|
|
|
|
public int size()
|
|
{
|
|
return store.size();
|
|
}
|
|
|
|
public Iterator<K> iterator()
|
|
{
|
|
return new Iterator<K>()
|
|
{
|
|
private final Iterator<Map.Entry<K,V>> it = store.iterator();
|
|
|
|
@Override
|
|
public boolean hasNext()
|
|
{
|
|
return it.hasNext();
|
|
}
|
|
|
|
@Override
|
|
public K next()
|
|
{
|
|
return it.next().getKey();
|
|
}
|
|
};
|
|
}
|
|
|
|
public String toString() {
|
|
return store.toString();
|
|
}
|
|
|
|
public static void main(String[] args)
|
|
{
|
|
LRWCache<String, String> cache = new LRWCache<>(4);
|
|
cache.put("a", "abhinav");
|
|
cache.put("b", "batman");
|
|
cache.put("c", "carol");
|
|
cache.put("z", "zellman");
|
|
System.out.println(cache);
|
|
|
|
cache.put("w", "walker");
|
|
System.out.println(cache);
|
|
|
|
cache.put("c", "carly");
|
|
System.out.println(cache);
|
|
|
|
cache.put("x", "xander");
|
|
System.out.println(cache);
|
|
}
|
|
|
|
}
|