Java通过LinkedHashMap实现LRU -----学习笔记

Java通过LinkedHashMap实现LRU -----学习笔记

import java.util.*;


public class Test<K,V> extends LinkedHashMap<K,V> {
    
    


    private int capacity;

    public Test(int capacity){
    
    
        super();
        this.capacity=capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
    
    
        //如果LinkedHashMap长度大于限定容量返回true,否则返回false
        return size() > capacity;
    }

    //测试
    public static void main(String[] args) {
    
    
        Test<Integer,Integer> test = new Test<>(3);
        test.put(1,2);
        test.put(2,3);
        test.put(3,4);
        for(Map.Entry<Integer,Integer> temp : test.entrySet()){
    
    
            System.out.println(temp.getKey()+" "+temp.getValue());
        }
        System.out.println("================================");
        test.put(4,5);
        for(Map.Entry<Integer,Integer> temp : test.entrySet()){
    
    
            System.out.println(temp.getKey()+" "+temp.getValue());
        }
        System.out.println("================================");
        System.out.println(test.get(2));
        System.out.println("================================");
        for(Map.Entry<Integer,Integer> temp : test.entrySet()){
    
    
            System.out.println(temp.getKey()+" "+temp.getValue());
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_41454682/article/details/112836184
今日推荐