Java – LRU caching using LinkedHashMap
•
Java
I try to use LinkedHashMap to implement LRU caching
Note that if you re insert the key into the map, the insertion order is not affected
But when I make the following expression
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); } }
Output is
{1=1,3=3}
This indicates that reinsertion does affect the order Does anyone know any explanation?
Solution
As @ Jeffrey said, you are using accessorder When creating a LinkedHashMap, the third parameter specifies how the order changes
"true for access-order,false for insertion-order"
For a more detailed implementation of LRU, you can take a look at this http://www.programcreek.com/2013/03/leetcode-lru-cache-java/
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码