LRU简单实现

用LinkedHashMap来实现

package com.yin.purchase.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

public class LRUMap<K,V> {


    /**
     * 最大缓存大小
     */
    private int cacheSize;

    private LinkedHashMap<K,V> cacheMap ;


    public LRUMap(int cacheSize) {
        this.cacheSize = cacheSize;

        cacheMap = new LinkedHashMap(16,0.75F,true){
            @Override
            protected boolean removeEldestEntry(Map.Entry eldest) {
                if (cacheSize + 1 == cacheMap.size()){
                    return true ;
                }else {
                    return false ;
                }
            }
        };
    }

    public void put(K key,V value){
        cacheMap.put(key,value) ;
    }
    public V get(K key){
        return cacheMap.get(key) ;
    }


    public Collection<Map.Entry<K, V>> getAll() {
        return new ArrayList<>(cacheMap.entrySet());
    }

    public static void main(String[] args) {
        LRUMap<String, Integer> map = new LRUMap(4);
        map.put("1", 1);
        map.put("2", 2);
        map.put("3", 3);
        map.put("4", 4);
        for (Map.Entry<String, Integer> e : map.getAll()) {
            System.out.print(e.getKey() + " : " + e.getValue() + "	");
        }
        System.out.println("");
        map.get("1");
        for (Map.Entry<String, Integer> e : map.getAll()) {
            System.out.print(e.getKey() + " : " + e.getValue() + "	");
        }
    }

}

输出结果:

1 : 1    2 : 2    3 : 3    4 : 4    
2 : 2    3 : 3    4 : 4    1 : 1    
Process finished with exit code 0
原文地址:https://www.cnblogs.com/yintingting/p/7450033.html