LRU:最近最久未使用
LinkedHashMap默认是不删除元素的,通过重写removeEldestEnrtry来实现最大容量
 1 public class LRUMap<K,V> extends LinkedHashMap {
 2 
 3     private static final long serialVersionUID = 7712857012453857193L;
 4 
 5     //最大容量
 6     public static int MAX_SIZE=20;
 7 
 8     public LRUMap(int initialCapacity, float loadFactor,boolean accessOrder){
 9         super(initialCapacity, loadFactor, accessOrder);
10     }
11 
12     /**
13      * 如果Map的尺寸大于设定的最大容量,返回true
14      * 再新加入对象时删除最老的对象
15      */
16     @Override
17     protected boolean removeEldestEntry(Map.Entry eldest) {
18         return size()>MAX_SIZE;
19     }
20 
21     public static void main(String[] args) {
22         Map<Integer,Integer> map = new LRUMap<>(10,0.75f,true);
23         LRUMap.MAX_SIZE=3;
24         map.put(1,1);
25         map.put(2,2);
26         map.put(3,3);
27         map.put(4,4);
28         map.put(5,5);
29         System.out.println(map.size());
30         for (Map.Entry<Integer,Integer> entry:map.entrySet()){
31             System.out.println(entry.getKey()+":"+entry.getValue());
32         }
33     }
34 }

运行结果:

3
3:3
4:4
5:5