LRU简介
内存淘汰策略:删除最近最少使用的
Java实现
import java.util.LinkedHashMap;
import java.util.Map;
public class LRUCache<K, V> extends LinkedHashMap<K,V> {
private final int CACHE_SIZE;
public LRUCache(int cache_size) {
super((int) Math.ceil(cache_size / 0.75), 0.75f, true);
CACHE_SIZE = cache_size;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > CACHE_SIZE;
}
}
用例
import java.util.Map;
public class LRUCacheTest {
public static void main(String[] args) {
LRUCache<Integer,String> map = new LRUCache<>(5);
map.put(1,"张三1");
map.put(2,"张三2");
map.put(3,"张三3");
map.put(4,"张三4");
map.get(1);
map.put(5,"张三5");
map.put(6,"张三6");
map.put(7,"张三7");
for(Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
}
}
}