The Java Collections Framework never stops to surprise me. When I started to look for suitable collections to store my cached objects I noticed an interesting protected method in the LinkedHashMap class:
protected boolean removeEldestEntry(Map.Entry eldest);Using this, implementing a fixed size "last recently used" collection is possible in just a few lines of code:
public class LruMap<K, V> extends LinkedHashMap<K, V> {
private final int limit;
public LruMap(int limit) {
super(16, 0.75f, true);
this.limit = limit;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > limit;
}
}
No comments:
Post a Comment