当前位置:网站首页>使用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);
}
}
边栏推荐
猜你喜欢

【yarn】CDP集群 Yarn配置capacity调度器批量分配

AI benchmark V5 ranking
![[蓝桥杯2017初赛]方格分割](/img/e9/e49556d0867840148a60ff4906f78e.png)
[蓝桥杯2017初赛]方格分割

02 staff information management after the actual project

About string immutability

Request object and response object analysis

Machine learning notes week02 convolutional neural network

Image recognition - pyteseract TesseractNotFoundError: tesseract is not installed or it‘s not in your path

MySQL and C language connection (vs2019 version)

4、安装部署Spark(Spark on Yarn模式)
随机推荐
L2-001 emergency rescue (25 points)
nodejs 详解
4、安装部署Spark(Spark on Yarn模式)
vs2019 第一个MFC应用程序
Codeforces Round #771 (Div. 2)
Summary of numpy installation problems
第4阶段 Mysql数据库
QT creator support platform
快来走进JVM吧
Stage 4 MySQL database
QT creator test
[NPUCTF2020]ReadlezPHP
Software I2C based on Hal Library
4. Install and deploy spark (spark on Yan mode)
yarn安装与使用
Solution of deleting path variable by mistake
Codeforces Round #771 (Div. 2)
【presto】presto 参数配置优化
Wangeditor rich text component - copy available
Pytorch基础