我试图使用LinkedHashMap实现LRU缓存。在LinkedHashMap的文档(http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html)中,它表示:
请注意,如果将密钥重新插入到映射中,则插入顺序不会受到影响。
但是当我做以下推
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}
这表明重新插入确实影响了订单。有人知道任何解释吗?
正如Jeffrey指出的那样,您正在使用accessOrder。创建LinkedHashMap时,第三个参数指定如何更改顺序。
"true for access-order, false for insertion-order"
有关LRU的详细实现,请查看此http://www.programcreek.com/2013/03/leetcode-lru-cache-java/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句