当前位置:网站首页>使用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);
}
}
边栏推荐
- Password free login of distributed nodes
- Software I2C based on Hal Library
- Antlr4 uses keywords as identifiers
- Machine learning notes week02 convolutional neural network
- Reading BMP file with C language
- SQL时间注入
- 數據庫高級學習筆記--SQL語句
- Error connecting to MySQL database: 2059 - authentication plugin 'caching_ sha2_ The solution of 'password'
- [yarn] CDP cluster yarn configuration capacity scheduler batch allocation
- Face recognition_ recognition
猜你喜欢

Wangeditor rich text reference and table usage

Software I2C based on Hal Library

Integration test practice (1) theoretical basis

Double to int precision loss

保姆级出题教程

MongoDB

解决安装Failed building wheel for pillow

Did you forget to register or load this tag

Solve the problem of installing failed building wheel for pilot

wangeditor富文本引用、表格使用问题
随机推荐
Solution of deleting path variable by mistake
[Kerberos] deeply understand the Kerberos ticket life cycle
AI benchmark V5 ranking
L2-004 这是二叉搜索树吗? (25 分)
02 staff information management after the actual project
Project practice - background employee information management (add, delete, modify, check, login and exit)
QT creator runs the Valgrind tool on external applications
Common regular expression collation
Machine learning -- census data analysis
[蓝桥杯2017初赛]包子凑数
Database advanced learning notes -- SQL statement
Codeforces Round #753 (Div. 3)
Learn winpwn (3) -- sEH from scratch
Codeforces Round #771 (Div. 2)
Software testing - interview question sharing
Vs2019 first MFC Application
encoderMapReduce 随手记
Word排版(小計)
Did you forget to register or load this tag
Learn winpwn (2) -- GS protection from scratch