用java的LinkedHashMap实现LRU

package LRU;

import java.util.*;

/**
 * LRU class
 *
 * @author wsy
 * @Date 2020/10/20 18:50
 */
public class LRU extends LinkedHashMap {
    private static float LOAD_FACTOR = 0.75f;
    private static int INIT_CAPACITY = 3;
    private float maxCapacity;
    public LRU(int maxCapacity){
        super(INIT_CAPACITY,LOAD_FACTOR,true);
        this.maxCapacity = maxCapacity;
    }

    @Override
    /**
     * 如果当前该函数返回true,表示应该删除EldestEntry。否则不删,继续扩容。
     */
    protected boolean removeEldestEntry(Map.Entry eldest) {
        if (size() > maxCapacity){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        LRU cache = new LRU(3);
        cache.put(1,null);
        cache.put(2,null);
        cache.put(3,null);
        cache.put(1,null);
        cache.put(4,null);
        for (Object object: cache.entrySet()) {
            System.out.println(object);//3 1 4
        }
    }

}

你可能感兴趣的:(java,LRU,LinkedHashMap)