直接看代码
public class LruTest extends LinkedHashMap<Integer,Integer> {
private final int capacity;
public LruTest(int initialCapacity) {
super(initialCapacity, 0.75f, true);// true 表示按照访问时间排序 false 按照插入顺序排序
this.capacity = initialCapacity;
}
public int get(int key) {
return super.getOrDefault(key,-1);
}
// 重写 removeEldestEntry方法 默认fasle
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size()> capacity;
}
public void put(int key, int value) {
super.put(key, value);
}
public static void main(String[] args) {
LruTest lruTest = new LruTest(4);
lruTest.put(1,1);
lruTest.put(2,2);
lruTest.put(3,3);
lruTest.put(4,4);
lruTest.get(3);
lruTest.get(2);
lruTest.put(5,5);// 3 2 5 4
lruTest.put(6,6);// 3 2 5 6
lruTest.put(7,7);// 2 5 6 7
System.out.println(lruTest);
}
}