这样会算过吗?我觉得不会算过
import java.util.LinkedHashMap;
import java.util.Map;
public class LRUCache<K, V> {
private final int capacity;
private final Map<K, V> cache;
public LRUCache(int capacity) {
this.capacity = capacity;
// 使用 LinkedHashMap 并设置访问顺序为 true ,以便按访问顺序存储
this.cache = new LinkedHashMap<>(capacity, 0.75f, true) {
@
Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > LRUCache.this.capacity;
}
};
}
// 获取缓存中的数据
public V get(K key) {
return cache.getOrDefault(key, null);
}
// 向缓存中添加数据
public void put(K key, V value) {
cache.put(key, value);
}
public void printCache() {
System.out.println(cache);
}
public static void main(String[] args) {
LRUCache<Integer, String> lruCache = new LRUCache<>(3);
lruCache.put(1, "A");
lruCache.put(2, "B");
lruCache.put(3, "C");
lruCache.printCache(); // {1=A, 2=B, 3=C}
System.out.println("Get 1: " + lruCache.get(1)); // A
lruCache.printCache(); // {2=B, 3=C, 1=A}
lruCache.put(4, "D");
lruCache.printCache(); // {3=C, 1=A, 4=D}
}
}