Java 实现一个简单的LRU

package test1.util;

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache<K, V> extends LinkedHashMap<K, V> {
    private final int capacity;

    public LRUCache(int capacity) {
        // 设置accessOrder为true,表示按照访问顺序排序
        super(capacity, 0.75f, true);
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        // 当缓存大小超过容量时,移除最久未使用的元素
        return size() > capacity;
    }

    public static void main(String[] args) {
        LRUCache<Integer, String> cache = new LRUCache<>(3);

        cache.put(1, "One");
        cache.put(2, "Two");
        cache.put(3, "Three");

        // 访问元素1,使其成为最近使用的元素
        System.out.println(cache.get(1)); // 输出: One

        // 添加新元素,触发LRU淘汰
        cache.put(4, "Four");

        // 输出缓存内容
        System.out.println(cache); // 输出: {1=One, 3=Three, 4=Four}
    }
}

  

posted @ 2025-01-08 16:29  r1-12king  阅读(22)  评论(0)    收藏  举报