Java 实现一个简单的LRU

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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 @   r1-12king  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2022-01-08 java 集合removeAll() 方法
2022-01-08 Java 中生成list的几种方法
2022-01-08 Java 中 CollectionUtils.subtract() 和 List.removeAll() 方法求差集的区别
2022-01-08 Java踩坑之List的removeAll方法
点击右上角即可分享
微信分享提示