欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用LinkedHashMap来实现LRU算法

程序员文章站 2022-06-19 12:14:00
LRU算法:即淘汰最近最少未使用的请求算法LinkedHashMap中除了具有链表和HashMap的特征之外,还具有实现LRU算法的一些特性。从其源码注解中可以得知:This kind of map is well-suited to building LRU caches. Invoking the {@code put}, {@code putIfAbsent}, {@code get}, {@code getOrDefault}, {@code compute}, {@code compute...

LRU算法:即淘汰最近最少未使用的请求算法

LinkedHashMap中除了具有链表和HashMap的特征之外,还具有实现LRU算法的一些特性。
从其源码注解中可以得知:
This kind of map is well-suited to building LRU caches. Invoking the {@code put}, {@code putIfAbsent}, {@code get}, {@code getOrDefault}, {@code compute}, {@code computeIfAbsent}, {@code computeIfPresent}, or {@code merge} methods results in an access to the corresponding entry (assuming it exists after the invocation completes).
下面是实现的代码:

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author yupeiyang
 *
 * 实现LRU算法
 */
public class LruDemo1<K,V> extends LinkedHashMap<K,V> {
    private int capacity; //缓存空间

    public LruDemo1(int capacity){
        //accessOrder : true表示访问顺序、false表示插入顺序
        super(capacity,0.75f,true);
        //super(capacity,0.75f,false);
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return super.size() > capacity;
    }

    public static void main(String[] args) {
        LruDemo1 lruDemo1 = new LruDemo1(3);

        lruDemo1.put(4,"e");
        lruDemo1.put(3,"c");
        lruDemo1.put(1,"a");
        lruDemo1.put(5,"f");
        lruDemo1.put(2,"b");

        System.out.println(lruDemo1.keySet());
        System.out.println(lruDemo1.values());

        lruDemo1.put(6,"g");

        System.out.println(lruDemo1.keySet());
        System.out.println(lruDemo1.values());
    }
}

执行结果:
使用LinkedHashMap来实现LRU算法

本文地址:https://blog.csdn.net/weixin_43157935/article/details/112003697