package handlers;
import com.sun.org.apache.bcel.internal.generic.LUSHR;
import java.util.LinkedHashMap;
import java.util.Map;
class LRU<K,V> extends LinkedHashMap<K,V>{
public LRU(){
super(max_entires, 0.75f, true);
}
public static final int max_entires = 3;
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > max_entires;
}
public static void main(String[] args) {
LRU lruCache = new LRU();
lruCache.put(1,3);
lruCache.put(2,5);
lruCache.put(3,5);
lruCache.put(4,77);
lruCache.put(5,7);
lruCache.put(6,5);
lruCache.put(7,7);
lruCache.put(8,5);
lruCache.put(4,77);
System.out.println(lruCache.get(7));
System.out.println(lruCache.get(8));
System.out.println(lruCache.get(4));
}
}
class LRUCache {
LinkedHashMap cache;
public LRUCache(int capacity) {
cache = new LinkedHashMap(capacity, 1.0F, true) {
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return this.size() > capacity;
}
};
}
//cache.getOrDefault(key, -1);
public int get(int key) {
return (int)cache.getOrDefault(key,-1);
}
public void put(int key, int value) {
cache.put(key, value);
}
public static void main(String[] args) {
LRUCache lruCache = new LRUCache(3);
lruCache.put(1,3);
lruCache.put(2,5);
lruCache.put(3,3);
lruCache.put(4,3);
lruCache.put(5,3);
lruCache.put(6,3);
lruCache.put(7,3);
lruCache.put(8,3);
System.out.println(lruCache);
}
}
package handlers;
import com.sun.org.apache.bcel.internal.generic.LUSHR;
import java.util.LinkedHashMap;
import java.util.Map;
class LRU<K,V> extends LinkedHashMap<K,V>{
public final int max_entires;
public LRU(int i){
max_entires = i;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > max_entires;
}
public static void main(String[] args) {
LRU lruCache = new LRU(5);
lruCache.put(1,3);
lruCache.put(2,5);
lruCache.put(3,5);
lruCache.put(4,77);
lruCache.put(5,7);
lruCache.put(6,5);
lruCache.put(7,7);
lruCache.put(8,5);
lruCache.put(4,77);
System.out.println(lruCache.get(7));
System.out.println(lruCache.get(6));
System.out.println(lruCache.get(4));
System.out.println(lruCache.get(3));
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。