当前位置:网站首页>使用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);
}
}
边栏推荐
- Test objects involved in safety test
- [蓝桥杯2021初赛] 砝码称重
- [Kerberos] deeply understand the Kerberos ticket life cycle
- Error reporting solution - io UnsupportedOperation: can‘t do nonzero end-relative seeks
- Learn winpwn (2) -- GS protection from scratch
- Machine learning -- census data analysis
- 使用lambda在循环中传参时,参数总为同一个值
- {one week summary} take you into the ocean of JS knowledge
- L2-007 家庭房产 (25 分)
- Mysql的索引实现之B树和B+树
猜你喜欢
vs2019 桌面程序快速入门
AcWing 1298. Solution to Cao Chong's pig raising problem
vs2019 第一个MFC应用程序
Learn winpwn (2) -- GS protection from scratch
{一周总结}带你走进js知识的海洋
02 staff information management after the actual project
Word排版(小計)
Request object and response object analysis
PHP - whether the setting error displays -php xxx When PHP executes, there is no code exception prompt
AcWing 1298.曹冲养猪 题解
随机推荐
Word排版(小计)
Machine learning notes week02 convolutional neural network
AcWing 242. A simple integer problem (tree array + difference)
Vs2019 desktop app quick start
Solution of deleting path variable by mistake
vs2019 使用向导生成一个MFC应用程序
{一周总结}带你走进js知识的海洋
When using lambda to pass parameters in a loop, the parameters are always the same value
Wangeditor rich text reference and table usage
encoderMapReduce 随手记
分布式節點免密登錄
常用正则表达式整理
AcWing 179.阶乘分解 题解
wangeditor富文本组件-复制可用
Valentine's Day flirting with girls to force a small way, one can learn
2019腾讯暑期实习生正式笔试
Codeforces Round #753 (Div. 3)
Software testing and quality learning notes 3 -- white box testing
TypeScript
小L的试卷