我试图使用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缓存
发布评论