1 public class LRUCache<K, V> extends LinkedHashMap<K, V> { 2 private final int CACHE_SIZE; 3 4 public LRUCache(int cacheSize){ 5 super((int)Math.ceil(cacheSize / 0.75) + 1,0.75f,true); 6 CACHE_SIZE = cacheSize; 7 } 8 9 @Override 10 protected boolean removeEldestEntry(Map.Entry<K, V> entity) { 11 return size() > CACHE_SIZE; 12 } 13 14 public static void main (String...args){ 15 var cache = new LRUCache<Long,String>(5); 16 cache.put(1L,"1L"); 17 cache.put(2L,"2L"); 18 cache.put(3L,"3L"); 19 cache.put(4L,"4L"); 20 cache.put(5L,"5L"); 21 System.out.println(cache); 22 cache.put(6L,"6L"); 23 cache.put(7L,"7L"); 24 cache.put(8L,"8L"); 25 cache.put(9L,"9L"); 26 cache.put(10L,"10L"); 27 System.out.println(cache); 28 cache.get(6L); 29 cache.get(10L); 30 cache.get(8L); 31 cache.get(9L); 32 cache.get(7L); 33 System.out.println(cache); 34 cache.put(11L,"11L"); 35 cache.put(12L,"12L"); 36 System.out.println(cache); 37 } 38 // 输出 39 // {1=1L, 2=2L, 3=3L, 4=4L, 5=5L} 40 // {6=6L, 7=7L, 8=8L, 9=9L, 10=10L} 41 // {6=6L, 10=10L, 8=8L, 9=9L, 7=7L} 42 // {8=8L, 9=9L, 7=7L, 11=11L, 12=12L} 43 }