public class LRUCache extends LinkedHashMap {
private final int CACHE_SIZE;
public LRUCache(int cacheSize){
super((int)Math.ceil(cacheSize / 0.75) + 1,0.75f,true);
CACHE_SIZE = cacheSize;
}
@Override
protected boolean removeEldestEntry(Map.Entry entity) {
return size() > CACHE_SIZE;
}
public static void main (String...args){
var cache = new LRUCache(5);
cache.put(1L,"1L");
cache.put(2L,"2L");
cache.put(3L,"3L");
cache.put(4L,"4L");
cache.put(5L,"5L");
System.out.println(cache);
cache.put(6L,"6L");
cache.put(7L,"7L");
cache.put(8L,"8L");
cache.put(9L,"9L");
cache.put(10L,"10L");
System.out.println(cache);
cache.get(6L);
cache.get(10L);
cache.get(8L);
cache.get(9L);
cache.get(7L);
System.out.println(cache);
cache.put(11L,"11L");
cache.put(12L,"12L");
System.out.println(cache);
}
// 输出
// {1=1L, 2=2L, 3=3L, 4=4L, 5=5L}
// {6=6L, 7=7L, 8=8L, 9=9L, 10=10L}
// {6=6L, 10=10L, 8=8L, 9=9L, 7=7L}
// {8=8L, 9=9L, 7=7L, 11=11L, 12=12L}
}