Use LinkedHashMap and override removeEldestEntry and make sure to use the
constructor that allows to accessOrder as true
Accessordered makes the map remove the least recently accessed item instead of the eldest.
All queries will alter the structure of the map, hence be a tiny bit slower.
Example:
public AccesOrderedLRUCache<V,K> extends LinkedHashMap<V,K>{
private final m_capacity;
public AccesOrderedLRUCache(int capacity) {
super(0.75*capacity, 0.75, true);
m_capacity = capacity;
}
@Override
protected boolean removeEldestEntry (Map.Entry<K,V> eldest) {
return size() > getCapacity();
}
public int getCapacity() {
return m_capacity;
}
}