当前位置:网站首页>Using LinkedHashMap to realize the caching of an LRU algorithm
Using LinkedHashMap to realize the caching of an LRU algorithm
2022-07-06 11:44:00 【Ride the wind to break the bug】
/**
* @author wdj
* Created on 2021/2/25 14:28
*/
public class LRUcache<K,V> extends LinkedHashMap<K,V> {
// Default cache value
private static final int DEFAULT_NODE_NUM = 11;
// Cache limit
private int capacityLimit;
LRUcache(){
this(DEFAULT_NODE_NUM);
}
public LRUcache(int capaticy){
// In turn : Initial capacity , Load factor , Which sort of access
// The third parameter :false, It means traversal in insertion order ( The default is false)/true, Then it means sorting by access order
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){
// If LinkedHashMap The length of reaches the cache capacity , Scavenging
return size()>capacityLimit;
}
// The test case
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);
// Cover the original (10,10), At this time, the cache capacity is still sufficient
cache.putKV(10,9);
System.out.println(cache);
// Add another node
cache.putKV(11,11);
// At this time, the data in the cache has changed , Removed the head node of the linked list
System.out.println(cache);
}
}
边栏推荐
- error C4996: ‘strcpy‘: This function or variable may be unsafe. Consider using strcpy_s instead
- QT creator runs the Valgrind tool on external applications
- 01 project demand analysis (ordering system)
- 保姆级出题教程
- Integration test practice (1) theoretical basis
- Library function -- (continuous update)
- 分布式節點免密登錄
- [NPUCTF2020]ReadlezPHP
- [蓝桥杯2020初赛] 平面切分
- [CDH] cdh5.16 configuring the setting of yarn task centralized allocation does not take effect
猜你喜欢
随机推荐
【yarn】Yarn container 日志清理
Solution to the practice set of ladder race LV1 (all)
Password free login of distributed nodes
yarn安装与使用
Linux yum安装MySQL
Word typesetting (subtotal)
wangeditor富文本引用、表格使用问题
搞笑漫画:程序员的逻辑
机器学习笔记-Week02-卷积神经网络
PHP - whether the setting error displays -php xxx When PHP executes, there is no code exception prompt
[MRCTF2020]套娃
误删Path变量解决
Pytoch Foundation
Codeforces Round #753 (Div. 3)
double转int精度丢失问题
L2-004 这是二叉搜索树吗? (25 分)
【yarn】CDP集群 Yarn配置capacity调度器批量分配
使用lambda在循环中传参时,参数总为同一个值
Valentine's Day flirting with girls to force a small way, one can learn
2019腾讯暑期实习生正式笔试