LinkedHashMap实现简单LRU算法
最近刷题的时候的时候看到了 LRU(Least Recently Used) 算法,于是乎网上找了一下发现使用java的LinkedHashMap实现非常简单, 结合了LinkedHashMap的源码看了下,下面直接贴代码,注释写的非常详细了。
public class LRUWithLinkedHashMap {
Map<Integer, Integer> cache;
int capacity;
public LRUWithLinkedHashMap(int capacity) {
this.capacity = capacity;
//加载因子 loadFactor : 0.75 当size() > capacity*loadFactor 时map会进行扩容
//加载因子过大时元素存储更加紧凑,会影响读取效率 加载因子过小会造成空间浪费
//实现LRU重点--accessOrder: true 根据访问顺序排序 默认false 根据插入顺序排序
this.cache = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true) {
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
//设置删除年长结点的触发条件为缓存满
return size() > capacity;
}
};
}
@Override
public String toString() {
StringBuilder list = new StringBuilder();
for (Integer integer : this.cache.values()) {
list.append(integer).append("->");
}
return list.substring(0, list.length() - 2);
}
public int get(int key) {
//getOrDefault 方法 key不存在时返回默认值-1
//根据构造方法中的accessOrder=true 在调用完get方法后会调用afterNodeAccess()排序
return cache.getOrDefault(key, -1);
}
public void put(int key, int value) {
//插入后会根据重写的removeEldestEntry()返回值判断是否删除年长节点
cache.put(key, value);
}
}