zoukankan      html  css  js  c++  java
  • LRU最少使用

      通过继承LinkedHashMap实现LRU:

    import java.util.LinkedHashMap;
    import java.util.Map;
    
    public class LRUCache<K, V> extends LinkedHashMap<K, V> {
    
        private int size;
    
        public LRUCache(int size) {
            super((int) Math.ceil(size / 0.75) + 1, 0.75f, true);
            this.size = size;
        }
    
        protected boolean removeEldestEntry(Map<K, V> eldest) {
            return size() > size;
        }
    }

    import com.alibaba.fastjson.JSON;
    
    public class LRUMain {
    
        public static void main(String[] args) {
            LRUCache lruCache = new LRUCache(10);
            lruCache.put("1", "1");
            lruCache.put("2", "2");
            lruCache.put("3", "3");
            lruCache.put("4", "4");
            lruCache.put("5", "5");
            lruCache.put("6", "6");
            System.out.println(JSON.toJSONString(lruCache));
            lruCache.get("2");
            System.out.println(JSON.toJSONString(lruCache));
            lruCache.get("5");
            lruCache.get("5");
            lruCache.get("5");
            lruCache.get("5");
            System.out.println(JSON.toJSONString(lruCache));
        }
    }

    {"1":"1","2":"2","3":"3","4":"4","5":"5","6":"6"}
    {"1":"1","3":"3","4":"4","5":"5","6":"6","2":"2"}
    {"1":"1","3":"3","4":"4","6":"6","2":"2","5":"5"}

    通过双向链表+map可以实现LRU

  • 相关阅读:
    learning scala pattern matching
    learning scala Case Classses
    simcom7600ce-t LBS function
    hadoop kafka learning url
    python 生成器
    计算机名称和IP地址
    批量压缩文件夹到Zip文件
    批量解压Zip文件
    创建本地作业
    方便不冗余的桌面文件夹
  • 原文地址:https://www.cnblogs.com/use-D/p/12622681.html
Copyright © 2011-2022 走看看