当前位置:网站首页>使用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);
}
}
边栏推荐
- Word排版(小计)
- PHP - whether the setting error displays -php xxx When PHP executes, there is no code exception prompt
- [AGC009D]Uninity
- [Flink] cdh/cdp Flink on Yan log configuration
- [Kerberos] deeply understand the Kerberos ticket life cycle
- JS array + array method reconstruction
- C语言读取BMP文件
- Vs2019 use wizard to generate an MFC Application
- Tcp/ip protocol (UDP)
- L2-006 树的遍历 (25 分)
猜你喜欢
wangeditor富文本引用、表格使用问题
MTCNN人脸检测
Summary of numpy installation problems
About string immutability
QT creator test
Vs2019 desktop app quick start
Case analysis of data inconsistency caused by Pt OSC table change
Error connecting to MySQL database: 2059 - authentication plugin 'caching_ sha2_ The solution of 'password'
vs2019 桌面程序快速入门
Integration test practice (1) theoretical basis
随机推荐
TypeScript
Summary of numpy installation problems
Learn winpwn (3) -- sEH from scratch
Word排版(小計)
Antlr4 uses keywords as identifiers
wangeditor富文本组件-复制可用
保姆级出题教程
Pytorch基础
MTCNN人脸检测
AcWing 1294.樱花 题解
How to build a new project for keil5mdk (with super detailed drawings)
Error connecting to MySQL database: 2059 - authentication plugin 'caching_ sha2_ The solution of 'password'
Software testing - interview question sharing
express框架详解
MySQL and C language connection (vs2019 version)
Password free login of distributed nodes
Base de données Advanced Learning Notes - - SQL statements
Pytoch Foundation
[Kerberos] deeply understand the Kerberos ticket life cycle
[Bluebridge cup 2021 preliminary] weight weighing