zoukankan      html  css  js  c++  java
  • 使用linkedhashmap实现LRU(最近最少使用缓存算法)

    import java.util.LinkedHashMap;
    import java.util.Map;
    
    public class LRUCache<K, V> extends LinkedHashMap<K, V> {
        private static final int MAX_CACHE_SIZE = 100;
    
        private int limit;
    
        public LRUCache() {
            this(MAX_CACHE_SIZE);
        }
    
        public LRUCache(int cacheSize) {
            super(cacheSize, 0.75f, true);
            this.limit = cacheSize;
        }
    
        public V save(K key, V val) {
            return put(key, val);
        }
    
        public V getOne(K key) {
            return get(key);
        }
    
        public boolean exists(K key) {
            return containsKey(key);
        }
    
        /**
         * 判断节点数是否超限
         * @param eldest
         * @return 超限返回 true,否则返回 false
         */
        @Override
        protected boolean removeEldestEntry(Map.Entry eldest) {
            return size() > limit;
        }
    
        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<K, V> entry : entrySet()) {
                sb.append(String.format("%s:%s ", entry.getKey(), entry.getValue()));
            }
            return sb.toString();
        }
    
        public static void main(String[] args){
            LRUCache<String, Integer> cache = new LRUCache<>(3);
    
            for (int i = 0; i < 10; i++) {
                cache.save("I" + i, i * i);
            }
    System.out.println(cache);
            System.out.println("插入10个键值对后,缓存内容为:");
            System.out.println(cache + "
    ");
    
            System.out.println("访问键值为I8的节点后,缓存内容为:");
            cache.getOne("I8");
            System.out.println(cache + "
    ");
    
            System.out.println("插入键值为I1的键值对后,缓存内容:");
            cache.save("I1", 1);
            System.out.println(cache);
            System.out.println("size:"+cache.size());
        }
    }
    

      

  • 相关阅读:
    python第三十二课——队列
    python第三十二课——栈
    python提示警告InsecureRequestWarning
    关于requests.exceptions.SSLError: HTTPSConnectionPool
    python第三十一课--递归(3.递归的弊端)
    01 redis特点及安装使用
    22 nginx配置与集群
    21-nginx单机1W并发优化
    20-ab压力测试及nginx性能统计模块
    19 大网站的优化思路
  • 原文地址:https://www.cnblogs.com/qinyios/p/11063960.html
Copyright © 2011-2022 走看看