当前位置:网站首页>使用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);
}
}
边栏推荐
- One click extraction of tables in PDF
- Knowledge Q & A based on Apache Jena
- Case analysis of data inconsistency caused by Pt OSC table change
- wangeditor富文本引用、表格使用问题
- Software I2C based on Hal Library
- [AGC009D]Uninity
- vs2019 桌面程序快速入门
- [Flink] cdh/cdp Flink on Yan log configuration
- Codeforces Round #771 (Div. 2)
- QT creator support platform
猜你喜欢
AcWing 1298. Solution to Cao Chong's pig raising problem
人脸识别 face_recognition
AcWing 1298.曹冲养猪 题解
Composition des mots (sous - total)
Rhcsa certification exam exercise (configured on the first host)
One click extraction of tables in PDF
Word排版(小計)
Reading BMP file with C language
第4阶段 Mysql数据库
wangeditor富文本引用、表格使用问题
随机推荐
wangeditor富文本引用、表格使用问题
AcWing 1298.曹冲养猪 题解
库函数--(持续更新)
Vs2019 use wizard to generate an MFC Application
[yarn] CDP cluster yarn configuration capacity scheduler batch allocation
【yarn】Yarn container 日志清理
MySQL与c语言连接(vs2019版)
ES6 promise object
[Blue Bridge Cup 2017 preliminary] buns make up
[NPUCTF2020]ReadlezPHP
jS数组+数组方法重构
Learning question 1:127.0.0.1 refused our visit
Solution of deleting path variable by mistake
【kerberos】深入理解kerberos票据生命周期
使用lambda在循环中传参时,参数总为同一个值
[Bluebridge cup 2021 preliminary] weight weighing
2020网鼎杯_朱雀组_Web_nmap
nodejs连接Mysql
Solution to the practice set of ladder race LV1 (all)
yarn安装与使用