zoukankan      html  css  js  c++  java
  • LRU简单实现

    用LinkedHashMap来实现

    package com.yin.purchase.dao;
    
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    public class LRUMap<K,V> {
    
    
        /**
         * 最大缓存大小
         */
        private int cacheSize;
    
        private LinkedHashMap<K,V> cacheMap ;
    
    
        public LRUMap(int cacheSize) {
            this.cacheSize = cacheSize;
    
            cacheMap = new LinkedHashMap(16,0.75F,true){
                @Override
                protected boolean removeEldestEntry(Map.Entry eldest) {
                    if (cacheSize + 1 == cacheMap.size()){
                        return true ;
                    }else {
                        return false ;
                    }
                }
            };
        }
    
        public void put(K key,V value){
            cacheMap.put(key,value) ;
        }
        public V get(K key){
            return cacheMap.get(key) ;
        }
    
    
        public Collection<Map.Entry<K, V>> getAll() {
            return new ArrayList<>(cacheMap.entrySet());
        }
    
        public static void main(String[] args) {
            LRUMap<String, Integer> map = new LRUMap(4);
            map.put("1", 1);
            map.put("2", 2);
            map.put("3", 3);
            map.put("4", 4);
            for (Map.Entry<String, Integer> e : map.getAll()) {
                System.out.print(e.getKey() + " : " + e.getValue() + "	");
            }
            System.out.println("");
            map.get("1");
            for (Map.Entry<String, Integer> e : map.getAll()) {
                System.out.print(e.getKey() + " : " + e.getValue() + "	");
            }
        }
    
    }

    输出结果:

    1 : 1    2 : 2    3 : 3    4 : 4    
    2 : 2    3 : 3    4 : 4    1 : 1    
    Process finished with exit code 0
  • 相关阅读:
    三层架构简单实例【转】
    排序 普通插入法排序
    排序 选择排序
    C#中的继承与覆盖
    排序 冒泡排序法
    c#使用Split分割字符串的几种方法
    GROUP BY,WHERE,HAVING之间的区别和用法
    递归 斐波那契数列
    【公众号系列】一文看懂税费改革
    【MM系列】SAP库龄报表逻辑理解
  • 原文地址:https://www.cnblogs.com/yintingting/p/7450033.html
Copyright © 2011-2022 走看看