当前位置:网站首页>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);
}
}
边栏推荐
猜你喜欢
vs2019 使用向导生成一个MFC应用程序
[Flink] Flink learning
[Blue Bridge Cup 2017 preliminary] grid division
Software testing and quality learning notes 3 -- white box testing
[蓝桥杯2017初赛]方格分割
Kept VRRP script, preemptive delay, VIP unicast details
解决安装Failed building wheel for pillow
QT creator test
[yarn] CDP cluster yarn configuration capacity scheduler batch allocation
第4阶段 Mysql数据库
随机推荐
Solution of deleting path variable by mistake
數據庫高級學習筆記--SQL語句
L2-007 家庭房产 (25 分)
误删Path变量解决
[NPUCTF2020]ReadlezPHP
[NPUCTF2020]ReadlezPHP
Wangeditor rich text component - copy available
ES6 promise object
AcWing 1294.樱花 题解
MATLAB学习和实战 随手记
Django running error: error loading mysqldb module solution
How to set up voice recognition on the computer with shortcut keys
Codeforces Round #771 (Div. 2)
[Flink] cdh/cdp Flink on Yan log configuration
分布式節點免密登錄
Antlr4 uses keywords as identifiers
Aborted connection 1055898 to db:
UDS learning notes on fault codes (0x19 and 0x14 services)
When using lambda to pass parameters in a loop, the parameters are always the same value
Connexion sans mot de passe du noeud distribué