通过继承LinkedHashMap实现LRU缓存

import java.util.LinkedHashMap;  
import java.util.Map;  
/** 
 * LinkedHashMap默认是不删除元素的,通过重写removeEldestEntry来实现最大容量 
 * @author bean 
 */  
public class LRUMap<K, V> extends LinkedHashMap<K, V> {  
    private static final long serialVersionUID = 6918023506928428613L;  
    // 最大容量  
    public static int MAX_SIZE = 10;  
  
    public LRUMap(int initialCapacity, float loadFactor, boolean accessOrder) {  
        super(initialCapacity, loadFactor, accessOrder);
    }  
  
    /** 
     * 如果Map的尺寸大于设定的最大容量,返回true,再新加入对象时删除最老的对象 
     */  
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {  
        return size() > MAX_SIZE;  
    }  
      
    public static void main(String[] args) {  
        Map<Integer, Integer> map=new LRUMap<Integer, Integer>(10,0.75f,true);  
        LRUMap.MAX_SIZE=4;  
        map.put(1, 1);  
        map.put(2, 2);  
        map.put(3, 3);  
        map.put(4, 4);  
        map.get(3);  
        map.put(5, 5);  
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {  
            System.err.println(entry.getKey());  
        }  
        //打印结果是 2 4 3 5 ,实现了LRU的功能  
    }  
}  

猜你喜欢

转载自blog.csdn.net/fzy629442466/article/details/84825853