使用LinkedHashMap实现LRU缓存 [英] Use LinkedHashMap to implement LRU cache
问题描述
我试图使用LinkedHashMap实现LRU缓存。
在LinkedHashMap的文档中( http://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 (http://docs.oracle.com/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的更详细实现,你可以看看这个
http://www.programcreek.com/2013/03/leetcode-lru-cache-java/
For more detailed implementation of LRU, you can look at this http://www.programcreek.com/2013/03/leetcode-lru-cache-java/
这篇关于使用LinkedHashMap实现LRU缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!