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

原文地址:https://www.cnblogs.com/use-D/p/12622681.html