当前位置:网站首页>Using LinkedHashMap to realize the caching of an LRU algorithm

Using LinkedHashMap to realize the caching of an LRU algorithm

2022-07-06 11:44:00 Ride the wind to break the bug

/**
 * @author wdj
 * Created on 2021/2/25 14:28
 */
public class LRUcache<K,V> extends LinkedHashMap<K,V> {
    // Default cache value 
    private static final int DEFAULT_NODE_NUM = 11;
    // Cache limit 
    private int capacityLimit;

    LRUcache(){
        this(DEFAULT_NODE_NUM);
    }

    public LRUcache(int capaticy){
        // In turn : Initial capacity , Load factor , Which sort of access 
        // The third parameter :false, It means traversal in insertion order ( The default is false)/true, Then it means sorting by access order 
        super(capaticy,0.75f,true);
        this.capacityLimit = capaticy;
    }

    public V putKV(K key,V val){
        return put(key,val);
    }

    public V getValue(K key){
        return get(key);
    }

    public boolean exists(K key){
        return containsKey(key);
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K,V> eldest){
        // If LinkedHashMap The length of reaches the cache capacity , Scavenging 
        return size()>capacityLimit;
    }

    // The test case 
    public static void main(String[]args){
        LRUcache<Object, Object> cache = new LRUcache<>();
        for (int i=0;i<11;i++){
            cache.putKV(i,i);
        }
        System.out.println(cache);
        cache.getValue(7);
        System.out.println(cache);
        cache.get(5);
        System.out.println(cache);
        // Cover the original (10,10), At this time, the cache capacity is still sufficient 
        cache.putKV(10,9);
        System.out.println(cache);
        // Add another node 
        cache.putKV(11,11);
        // At this time, the data in the cache has changed , Removed the head node of the linked list 
        System.out.println(cache);
    }

}
原网站

版权声明
本文为[Ride the wind to break the bug]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060913128150.html