1. 程式人生 > 其它 >使用LinkedHashMap來實現LRU演算法

使用LinkedHashMap來實現LRU演算法

技術標籤:# java集合演算法連結串列java

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());
    }
}

執行結果:
在這裡插入圖片描述