当前位置:网站首页>使用LinkedHashMap实现一个LRU算法的缓存
使用LinkedHashMap实现一个LRU算法的缓存
2022-07-06 09:15:00 【乘风破BUG】
/**
* @author wdj
* Created on 2021/2/25 14:28
*/
public class LRUcache<K,V> extends LinkedHashMap<K,V> {
//默认缓存值
private static final int DEFAULT_NODE_NUM = 11;
//缓存限定值
private int capacityLimit;
LRUcache(){
this(DEFAULT_NODE_NUM);
}
public LRUcache(int capaticy){
//依次为:初始容量,负载因子,采用哪种访问排序
//第三个参数:false,则表示按插入顺序遍历(默认为false)/true,则表示按访问顺序排序
super(capaticy,0.75f,true);
this.capacityLimit = capaticy;
}
public V putKV(K key,V val){
return put(key,val);
}
public V getValue(K key){
return get(key);
}
public boolean exists(K key){
return containsKey(key);
}
@Override
protected boolean removeEldestEntry(Map.Entry<K,V> eldest){
//如果LinkedHashMap的长度达到缓存容量,进行清除
return size()>capacityLimit;
}
//测试用例
public static void main(String[]args){
LRUcache<Object, Object> cache = new LRUcache<>();
for (int i=0;i<11;i++){
cache.putKV(i,i);
}
System.out.println(cache);
cache.getValue(7);
System.out.println(cache);
cache.get(5);
System.out.println(cache);
//覆盖原来的(10,10),此时缓存容量依旧够用
cache.putKV(10,9);
System.out.println(cache);
//再增加一个节点
cache.putKV(11,11);
//此时缓存中的数据已经发生变化,移除掉了链表的头节点
System.out.println(cache);
}
}
边栏推荐
猜你喜欢
Introduction and use of automatic machine learning framework (flaml, H2O)
4、安装部署Spark(Spark on Yarn模式)
vs2019 第一个MFC应用程序
Error connecting to MySQL database: 2059 - authentication plugin 'caching_ sha2_ The solution of 'password'
Cookie setting three-day secret free login (run tutorial)
Word排版(小计)
UDS learning notes on fault codes (0x19 and 0x14 services)
02 staff information management after the actual project
[yarn] yarn container log cleaning
AI benchmark V5 ranking
随机推荐
AcWing 1294.樱花 题解
Learning question 1:127.0.0.1 refused our visit
AcWing 1298.曹冲养猪 题解
Aborted connection 1055898 to db:
Julia 1.6 1.7 common problem solving
Tcp/ip protocol (UDP)
What does usart1 mean
{一周总结}带你走进js知识的海洋
Learn winpwn (2) -- GS protection from scratch
[Flink] Flink learning
L2-007 家庭房产 (25 分)
DICOM: Overview
How to set up voice recognition on the computer with shortcut keys
Password free login of distributed nodes
C语言读取BMP文件
Error connecting to MySQL database: 2059 - authentication plugin 'caching_ sha2_ The solution of 'password'
Software testing - interview question sharing
01 project demand analysis (ordering system)
TypeScript
[蓝桥杯2021初赛] 砝码称重