LRU算法Java实现

    public class LRUCache {
    private LinkedHashMap map;
    private int capacity;
    public LRUCache(int capacity){
    this.capacity = capacity;
    map = new LinkedHashMap<>();
    }
    public int get(int key){
    Integer value = map.get(key);
    if(map.get(key)==null){
    value = -1;
    }
    else{
    map.put(key,map.remove(key));
    }
    return value;
    }
    public void put(int key,int value)
    {
    if(map.containsKey(key)){
    map.remove(key);
    }
    map.put(key,value);
    if(map.size()>capacity){
    Iterator iterator = map.keySet().iterator();
    Integer next = iterator.next();
    map.remove(next);
    }
    }

    1. **public static void **main(String[] args) {<br /> LRUCache cache = **new **LRUCache(2 );
    2. cache.put(2, 1);<br /> cache.put(1, 1);<br /> cache.put(2, 3);_//作废2=1<br /> _cache.put(4, 1);_//作废1=1
    3. _System.**_out_**.println(cache.get(1));_//-1<br /> _System.**_out_**.println(cache.get(2));_//3<br /> _}<br />}