最近在学习缓存算法,就自己用java实现了一个LRU缓存算法,其实LRU可以直接用LinkedHashMap直接实现,本文采用HashMap来进行构造代码如下:
*public class LRUCache<K,V>{
private class CacheElemet<K,V>{
private CacheElemet before;
private CacheElemet next;
private K key;
private V value;
public CacheElemet(K key,V value) {
this.key=key;
this.value=value;
}
}
private int capacity=16;
private HashMap<K,CacheElemet> hs;
private CacheElemet first=null;
private CacheElemet last=null;
public LRUCache(){
hs=new HashMap<K,CacheElemet>(capacity);
}
public LRUCache(int mCapacity) {
this.capacity=capacity;
hs=new HashMap<K,CacheElemet>(capacity);
}
public V get(K key) {
if(!hs.containsKey(key)) {
return null;
}
CacheElemet current=hs.get(key);
current.before.next=current.next;
current.next.before=current.before;
addToLast(current);
return (V)current.value;
}
public void put(K key,V value) {
if(hs.size()==0) {
first=new CacheElemet(-1,-1);
last=new CacheElemet(-1,-1);
first.next=last;
first.before=last;
last.next=first;
last.before=first;
hs.put(null,first);
hs.put(null,last);;
}
if(hs.containsKey(key)) {
hs.get(key).value=value;
return;
}
if(hs.size()==capacity) {
hs.remove(first.next);
first.next=first.next.next;
first.next.before=first;
}
CacheElemet elemet=new CacheElemet<K,V>(key, value);
hs.put(key, elemet);
addToLast(elemet);
}
public void addToLast(CacheElemet element) {
element.before=last.before;
last.before=element;
last.before.next=element;
element.next=last;
}
}*