public class LRUCache <K, V> extends LinkedHashMap<K, V> {
private int maxEntries;
public LRUCache(int maxEntries) {
super(16, 0.75f, true);
this.maxEntries = maxEntries;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxEntries;
}
}
使用方法
public class CacheUtils {
private static LRUCache<String, String> cache = new LRUCache<>(8); //存储长度
public static void put(String key, String value) {
cache.put(key, value);
}
public static String get(String key) {
return cache.get(key);
}
public static void main(String[] args) {
for (int i = 0; i <= 9; i++) {
cache.put("key" + i, "abc");
}
System.out.println(cache);
cache.get("key2");
System.out.println(cache);
cache.put("key" + 10, "abc");
cache.put("key" + 11, "abc");
System.out.println(cache);
}
}