LRU算法:最近最少使用淘汰算法(Least Recently Used)。LRU是淘汰最长时间没有被使用的缓存(即使该缓存被访问的次数最多)。
代码如下:
import java.util.*;
public class LRUCache {
int cap;
Map<String, String> values;
Set<String> position;
public LRUCache(int cap) {
this.cap = cap;
values = new HashMap<>(cap);
position = new LinkedHashSet<>(cap);
}
public String get(String key) {
String value = null;
if (values.containsKey(key)) {
value = values.get(key);
position.remove(key);
position.add(key);
}
return value;
}
public void put(String key, String value) {
if (position.size() == cap) {
String firstKey = position.iterator().next();
position.remove(firstKey);
values.remove(firstKey);
}
position.add(key);
values.put(key, value);
}
public Map<String, String> getValues() {
return values;
}
public Set<String> getPosition() {
return position;
}
}
测试:
LRUCache lruCache = new LRUCache(4);
lruCache.put("a","a");
lruCache.put("b","b");
lruCache.put("c","c");
lruCache.put("d","d");
System.out.println("position:"+lruCache.getPosition());
System.out.println("values:"+lruCache.getValues());
lruCache.put("e","e");
System.out.println("position:"+lruCache.getPosition());
System.out.println("values:"+lruCache.getValues());
输出:
position:[a, b, c, d]
values:{a=a, b=b, c=c, d=d}
position:[b, c, d, e]
values:{b=b, c=c, d=d, e=e}
|