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

In the era of DFI dividends, can TGP become a new benchmark for future DFI?

QT creator custom build process

快来走进JVM吧

Vs2019 desktop app quick start

4. Install and deploy spark (spark on Yan mode)

{一周总结}带你走进js知识的海洋

error C4996: ‘strcpy‘: This function or variable may be unsafe. Consider using strcpy_ s instead

How to configure flymcu (STM32 serial port download software) is shown in super detail

MySQL and C language connection (vs2019 version)

Linux yum安装MySQL
随机推荐
Test objects involved in safety test
[蓝桥杯2021初赛] 砝码称重
人脸识别 face_recognition
机器学习笔记-Week02-卷积神经网络
数据库面试常问的一些概念
2019 Tencent summer intern formal written examination
Linux yum安装MySQL
Why can't STM32 download the program
Funny cartoon: Programmer's logic
[CDH] modify the default port 7180 of cloudera manager in cdh/cdp environment
Did you forget to register or load this tag
C语言读取BMP文件
Machine learning -- census data analysis
2019腾讯暑期实习生正式笔试
Tcp/ip protocol (UDP)
Number game
AI benchmark V5 ranking
Integration test practice (1) theoretical basis
AcWing 242. A simple integer problem (tree array + difference)
[yarn] yarn container log cleaning