使用LinkedHashMap实现LRU缓存

编程入门 行业动态 更新时间:2024-10-09 12:35:01
本文介绍了使用LinkedHashMap实现LRU缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图使用LinkedHashMap实现LRU缓存。 在LinkedHashMap的文档中( docs.oracle。 com / javase / 7 / docs / api / java / util / LinkedHashMap.html ),它说:

I was trying to implement a LRU cache using LinkedHashMap. In the documentation of LinkedHashMap (docs.oracle/javase/7/docs/api/java/util/LinkedHashMap.html), it says:

请注意,插入顺序不是如果将某个密钥重新插入地图中会受到影响。

但是当我执行以下操作时

But when I do the following puts

public class LRUCache<K, V> extends LinkedHashMap<K, V> { private int size; public static void main(String[] args) { LRUCache<Integer, Integer> cache = LRUCache.newInstance(2); cache.put(1, 1); cache.put(2, 2); cache.put(1, 1); cache.put(3, 3); System.out.println(cache); } private LRUCache(int size) { super(size, 0.75f, true); this.size = size; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > size; } public static <K, V> LRUCache<K, V> newInstance(int size) { return new LRUCache<K, V>(size); } }

输出

{1=1, 3=3}

这表示重新插入确实影响了订单。 有人知道任何解释吗?

Which indicates that the re-inserted did affected the order. Does anybody know any explanation?

推荐答案

正如杰弗里所指出的那样,您正在使用accessOrder。创建LinkedHashMap时,第三个参数指定顺序的更改方式。

As pointed out by Jeffrey, you are using accessOrder. When you created the LinkedHashMap, the third parameter specify how the order is changed.

"true for access-order, false for insertion-order"

有关LRU的更详细实现,你可以看看这个 www.programcreek/2013/03/leetcode-lru-cache-java/

For more detailed implementation of LRU, you can look at this www.programcreek/2013/03/leetcode-lru-cache-java/

更多推荐

使用LinkedHashMap实现LRU缓存

本文发布于:2023-11-30 21:46:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651568.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   LinkedHashMap   LRU

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!