使用LinkedHashMap实现的LRU算法,算是一种偷懒吧.
public class LRUCache < K, V > extends java.util.LinkedHashMap < K, V > {
private static final long serialVersionUID = 1L;
private int capacity;
public LRUCache(int capacity) {
super(capacity+1, 1.0f, true); // Pass 'true' for accessOrder.
this.capacity = capacity;
}
protected boolean removeEldestEntry(java.util.Map.Entry<K,V> entry) {
return (size() > this.capacity);
}
public V getValue(K key) {
if(this.keySet().contains(key)){
V value = this.get(key);
this.put(key, value);
return value;
}else{
return null;
}
}
public void setValue(K key, V value) {
this.put(key, value);
}
}