java基础-怎么实现LRU算法

时光毁灭记忆、已成空白 提交于 2019-12-04 20:38:47
 1 public class LRUCache<K, V> extends LinkedHashMap<K, V> {
 2    private final int CACHE_SIZE;
 3 
 4    public LRUCache(int cacheSize){
 5       super((int)Math.ceil(cacheSize / 0.75) + 1,0.75f,true);
 6       CACHE_SIZE = cacheSize;
 7    }
 8 
 9    @Override
10    protected boolean removeEldestEntry(Map.Entry<K, V> entity) {
11       return size() > CACHE_SIZE;
12    }
13 
14    public static void main (String...args){
15       var cache = new LRUCache<Long,String>(5);
16       cache.put(1L,"1L");
17       cache.put(2L,"2L");
18       cache.put(3L,"3L");
19       cache.put(4L,"4L");
20       cache.put(5L,"5L");
21       System.out.println(cache);
22       cache.put(6L,"6L");
23       cache.put(7L,"7L");
24       cache.put(8L,"8L");
25       cache.put(9L,"9L");
26       cache.put(10L,"10L");
27       System.out.println(cache);
28       cache.get(6L);
29       cache.get(10L);
30       cache.get(8L);
31       cache.get(9L);
32       cache.get(7L);
33       System.out.println(cache);
34       cache.put(11L,"11L");
35       cache.put(12L,"12L");
36       System.out.println(cache);
37    }
38 //  输出
39 // {1=1L, 2=2L, 3=3L, 4=4L, 5=5L}
40 // {6=6L, 7=7L, 8=8L, 9=9L, 10=10L}
41 // {6=6L, 10=10L, 8=8L, 9=9L, 7=7L}
42 // {8=8L, 9=9L, 7=7L, 11=11L, 12=12L}
43 }
View Code

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!