zoukankan      html  css  js  c++  java
  • java实现极简的LRU算法

    import java.util.LinkedHashMap;
    import java.util.Map;
     
    /**
     * LRU (Least Recently Used) 
     */
    public class LRUCache<K, V> extends LinkedHashMap<K, V> {
        /**

    */
    private static final long serialVersionUID = 1L;
    //缓存大小
        private int cacheSize;
     
        public LRUCache(int cacheSize) {
            //第三个参数true是关键
            super(10, 0.75f, true);
            this.cacheSize = cacheSize;
        }
     
        /**
         * 缓存是否已满
         */
        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            boolean r = size() > cacheSize;
            if(r){
                System.out.println("清除缓存key:"+eldest.getKey());
            }
            return r;
        }

        //测试

        public static void main(String[] args) {
            LRUCache<String, String> cache = new LRUCache<String, String>(5);
            cache.put("1", "1");
            cache.put("2", "2");
            cache.put("3", "3");
            cache.put("4", "4");
            cache.put("5", "5");
     
            System.out.println("初始:");
            System.out.println(cache.keySet());
            System.out.println("访问3:");
            cache.get("3");
            System.out.println(cache.keySet());
            System.out.println("访问2:");
            cache.get("2");
            System.out.println(cache.keySet());
            System.out.println("增加数据6,7:");
            cache.put("6", "6");
            cache.put("7", "7");
            System.out.println(cache.keySet());
        }

    }


    运行结果如下:

    初始化:
    [1, 2, 3, 4, 5]
    访问3:
    [1, 2, 4, 5, 3]
    访问2:
    [1, 4, 5, 3, 2]
    增加数据6,7:
    清除缓存key:1
    清除缓存key:4
    [5, 3, 2, 6, 7]

  • 相关阅读:
    leetcode 131. Palindrome Partitioning
    leetcode 526. Beautiful Arrangement
    poj 1852 Ants
    leetcode 1219. Path with Maximum Gold
    leetcode 66. Plus One
    leetcode 43. Multiply Strings
    pytorch中torch.narrow()函数
    pytorch中的torch.repeat()函数与numpy.tile()
    leetcode 1051. Height Checker
    leetcode 561. Array Partition I
  • 原文地址:https://www.cnblogs.com/dailidong/p/7571178.html
Copyright © 2011-2022 走看看