利用LinkedHashMap进行重写,实现LRU作为缓存字典
1、代码实现
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 利用LinkedHashMap进行重写,实现LRU作为缓存字典
*
* @param <K> key
* @param <V> value
* @date 2024-04-10 09:42
**/
public class LRUCache<K, V> extends LinkedHashMap<K, V> {
/**
* 最大容量
*/
private final int maxCapacity;
public LRUCache(int maxCapacity) {
super(maxCapacity, 0.75F, true);
this.maxCapacity = maxCapacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
// 大于最大容量maxCapacity时,移除最前元素
return super.size() > maxCapacity;
}
}
2、测试
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class LRUCacheTest {
@Test
public void testLru() {
// 最大容量为3
LRUCache<Integer, Integer> cache = new LRUCache<>(3);
cache.put(0, 0);
cache.put(1, 1);
cache.put(2, 2);
cache.put(3, 3); // 该操作会使得密钥 0 作废
Assertions.assertNull(cache.get(0));
cache.put(4, 4); // 该操作会使得密钥 1 作废
Assertions.assertNull(cache.get(1));
Assertions.assertEquals(3, cache.size());
Assertions.assertEquals(2, cache.get(2));
Assertions.assertEquals(3, cache.get(3));
Assertions.assertEquals(4, cache.get(4));
}
}
标签:get,cache,LRU,Assertions,简单,put,maxCapacity,LinkedHashMap
From: https://blog.csdn.net/yyp0719/article/details/137584538