LRU and FIFO implementations using LinkedHashMap
Not many knows, but the LinkedHashMap class allows you to implement both an LRU and FIFO queues almost without coding!
Here's how it's done:
Instantiating LinkedHashMap with the 3rd parameter passed as true in this c'tor:
public LinkedHashMap(int initialCapacity,
causes the map to become an LRU map. That's because the map is ordered by access-order.
But passing the 3rd parameter as false makes it a FIFO, because the map is ordered by insertion order.
So if you want to use it as an FIFO, do the following:
HashMap map = new LinkedHashMap(0, 0.75F, false)
And if you want to use it as a LRU, use the following class that extends the LinkedHashMap class and overrides its removeEldestEntry method:
private class LRUMap<K, V> extends LinkedHashMap<K, V>
private int maxCapacity;
public LRUMap(int maxCapacity)
super(0, 0.75F, true);
this.maxCapacity = maxCapacity;
protected boolean removeEldestEntry(Map.Entry<K, V> eldest)
return size() >= this.maxCapacity;
Note that in the c'tor of the LRU class, a bollean true flag is passed, unlike in the FIFO example, where false is passed.
We will contact you as soon as possible.