背景
今天看到敖丙大佬的redis中,提到了lru算法,才知道原来Java自带的LinkedHashMap中其实自带了LRU(Least recently used,最近最少使用)算法的实现。
官方注释中有说明,removeEldestEntry方法在put和putAll的时候会调用,自己用idea跟踪发现也确实如此
因此如果面试的时候让我们手写一个LRU算法,可以直接基于LinkedHashMap去实现,主要是重写removeEldestEntry
public class LRUCache<K,V> extends LinkedHashMap<K,V> {
private int capacity;
public LRUCache(int initialCapacity) {
super(initialCapacity);
this.capacity = initialCapacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}
public static void main(String[] args) {
LRUCache<String, String> lruCache = new LRUCache<>(5);
lruCache.put("a", "1");
lruCache.put("b", "2");
lruCache.put("c", "3");
lruCache.put("d", "4");
lruCache.put("e", "5");
lruCache.put("f", "6");
lruCache.entrySet().forEach(i->{
System.out.println(i.getKey() + ":"+ i.getValue());
});
}
## 输出结果中第一次加入的被remove掉了
b:2
c:3
d:4
e:5
f:6
Process finished with exit code 0