import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author lucas
* @create 2021-08-09 19:53
* @description LRU算法的基础实现
*/
public class LRUCacheDemo<k, v> extends LinkedHashMap<k, v> {
/**
* 1.确定初始容量
* 2.初始化构造器的,容量capacity
* 3.删除操作
*/
private int capacity; //最大容量
public LRUCacheDemo(int capacity) {
/**
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @param accessOrder the ordering mode - <tt>true</tt> for
* access-order, <tt>false</tt> for insertion-order 访问顺序
*/
super(capacity, 0.75F, false);
this.capacity = capacity;
}
// 默认的构造方法基于,负载因子和顺序
// public LRUCacheDemo(int initialCapacity, float loadFactor, boolean accessOrder, int capacity) {
// super(initialCapacity, loadFactor, accessOrder);
// this.capacity = capacity;
// }
//删除操作
@Override
protected boolean removeEldestEntry(Map.Entry<k, v> eldest) {
return super.size() > capacity;
}
public static void main(String[] args) {
LRUCacheDemo lruCacheDemo = new LRUCacheDemo(3);
lruCacheDemo.put(1, "a");
lruCacheDemo.put(2, "b");
lruCacheDemo.put(3, "c");
System.out.println(lruCacheDemo.keySet());
lruCacheDemo.put(4, "d");
System.out.println("增加第四个后,列表是"+lruCacheDemo.keySet());
/**
* [1, 2, 3]
* 增加第四个后,列表是[2, 3, 4]
* 解析: 当前第四个进来之后,4这个值将最近最少使用的直接踢出去
*/
System.out.println("--------------------------------------------");
lruCacheDemo.put(3, "d");
System.out.println(lruCacheDemo.keySet());
lruCacheDemo.put(3, "d");
System.out.println(lruCacheDemo.keySet());
lruCacheDemo.put(3, "d");
System.out.println(lruCacheDemo.keySet());
/***
* [2, 4, 3]
* [2, 4, 3]
* [2, 4, 3]
* 最近一直使用的,3的值最频繁,放在最右侧
*/
System.out.println("--------------------------------------------");
lruCacheDemo.put(5, "d");
System.out.println(lruCacheDemo.keySet());
/**
* [4, 3, 5]
* 5,进入之后,直接将最少使用的2挤出去
*/
/** 访问顺序(accessOrder)为ture
* [1, 2, 3]
* 增加第四个后,列表是[2, 3, 4]
* --------------------------------------------
* [2, 4, 3]
* [2, 4, 3]
* [2, 4, 3]
* --------------------------------------------
* [4, 3, 5]
*/
```js
评论