LRU

244 阅读1分钟
public class LRUCache<K, V> extends LinkedHashMap<K, V> {

    public int size;

    /**
     * @param initialCapacity 容量上限
     * @param loadFactor      负载因子
     * @param accessOrder     为 true 表示让 linkedHashMap 按照访问顺序来进行排序,最近访问的放在头部,最老访问的放在尾部
     */
    public LRUCache(int initialCapacity, float loadFactor, boolean accessOrder) {
        // 该构造函数意在构造一个指定初始容量和指定负载因子的具有指定迭代顺序的LinkedHashMap
        super(initialCapacity, loadFactor, accessOrder);
        this.size = initialCapacity;
    }

    /**
     * 当LRU元素超过容量上限size后,删除最不经常使用的
     *
     * @param eldest
     * @return
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > size;
    }


    public static void main(String[] args) {
        LRUCache<String, String> lruCache = new LRUCache<String, String>(5, 0.75f, true);
        lruCache.put("a", "a");
        lruCache.put("b", "b");
        lruCache.put("c", "c");
        lruCache.put("d", "d");
        lruCache.put("e", "e");

        System.out.println(lruCache);
        System.out.println("-----------");
        lruCache.get("b");
        System.out.println(lruCache);
        System.out.println("-----------");
        lruCache.put("f", "f");
        lruCache.put("g", "g");
        System.out.println(lruCache);
    }
}