LRU缓存机制
题意:构造一个有LRU缓存机制的容器即写一个类并实现get和put
通过jdk中的LinkedHashMap中的构造函数我们可以发现,jdk已经实现了LRU这一机制了
LinedHashMap的构造函数如下:
public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
我们可以根据设置accessOrder变量来实现容器的LRU机制,对get和put的实现也是基于这一机制
代码如下:
package com.ischen.demo.utils.leetcode;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
/**
* @Author:ischen
* @Date 2019/7/29 10:18
* @Describe
*/
public class LRUCache {
HashMap<Integer,Integer> map;
int size;
public LRUCache(int capacity) {
size = capacity;
map = new LinkedHashMap<Integer, Integer>(capacity,0.75f,true);
}
public int get(int key) {
return map.containsKey(key)?map.get(key):-1;
}
public void put(int key, int value) {
if(map.containsKey(key)){
map.put(key,value);
return;
}
if(map.size()>=size){
Iterator<Integer> i = map.keySet().iterator();
if(i.hasNext()){
map.remove(i.next());
}
}
map.put(key,value);
}
public static void main(String[] args) {
LRUCache cache = new LRUCache(2);
System.out.println(cache.get(2));
cache.put(2,6);
System.out.println(cache.get(1));
cache.put(1,5);
cache.put(1,2);
System.out.println(cache.get(1));
System.out.println(cache.get(2));
}
}