使用linkedhashmap实现LRU(最近最少使用缓存算法)
2024-09-01 00:02:54
import java.util.LinkedHashMap;
import java.util.Map; public class LRUCache<K, V> extends LinkedHashMap<K, V> {
private static final int MAX_CACHE_SIZE = 100; private int limit; public LRUCache() {
this(MAX_CACHE_SIZE);
} public LRUCache(int cacheSize) {
super(cacheSize, 0.75f, true);
this.limit = cacheSize;
} public V save(K key, V val) {
return put(key, val);
} public V getOne(K key) {
return get(key);
} public boolean exists(K key) {
return containsKey(key);
} /**
* 判断节点数是否超限
* @param eldest
* @return 超限返回 true,否则返回 false
*/
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > limit;
} @Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Map.Entry<K, V> entry : entrySet()) {
sb.append(String.format("%s:%s ", entry.getKey(), entry.getValue()));
}
return sb.toString();
} public static void main(String[] args){
LRUCache<String, Integer> cache = new LRUCache<>(3); for (int i = 0; i < 10; i++) {
cache.save("I" + i, i * i);
}
System.out.println(cache);
System.out.println("插入10个键值对后,缓存内容为:");
System.out.println(cache + "\n"); System.out.println("访问键值为I8的节点后,缓存内容为:");
cache.getOne("I8");
System.out.println(cache + "\n"); System.out.println("插入键值为I1的键值对后,缓存内容:");
cache.save("I1", 1);
System.out.println(cache);
System.out.println("size:"+cache.size());
}
}
最新文章
- Cloud Engine:大杀器如何炼成
- Asp.Net Core--基于声明的授权
- Tomcat与Jre绿色环境配置(生产环境)
- maven导入本地jar包
- HtmlAgilityPack---Html解析框架
- 利用 Process Monitor 找出某个 Windows 选项所对应的注册表值
- RelativeLayout布局
- 浙江理工2015.12校赛-A
- Linux运维命令之一
- window下部署php_redis扩展
- [android]如何让TextView使用超链接
- 51nod动态规划-----矩阵取数
- HDU1247 Hat’s Words(Trie的动态内存版本)
- [Angular 2] Handling Clicks and Intervals Together with Merge
- Set up HTTP/2 server with Spring Boot 【基于Spring boot搭建http2.0服务器】
- 【渗透课程】第二篇上-http请求协议的简单描述
- LeetCode 543. Diameter of Binary Tree (二叉树的直径)
- Tomcat 集群中 实现session 共享的三种方法
- vue-cli3.0怎么修改端口?
- 苹果ANCS协议学习【转】