链表:手写LRU缓存
LRU真实场景一般采用LinkedHashMap来实现。
链表:LRU缓存LinkedHashMap实现
import java.util.HashMap;
import java.util.Map;
/**
* LRU是Least Recently Used 近期最少使用算法
* 访问不频繁的在前面,访问较频繁的在后面
*/
public class LRUCache {
/*定义自己的缓存节点*/
private class CacheNode {
CacheNode prev;//前节点
CacheNode next;//后节点
Object key;//键
Object value;//值
public CacheNode(Object key, Object value) {
this.key = key;
this.value = value;
this.prev = null;
this.next = null;
}
}
private int capacity;//LRUCache容量,可以放置多少CacheNode
private Map<Object, CacheNode> valueNodeMap = new HashMap();//定义HashMap来找到CacheNode,时间复杂度T(n)=O(n1)
private CacheNode head = new CacheNode(-1, -1);//dummy头节点标识
private CacheNode tail = new CacheNode(-1, -1);//dummy尾节点标识
public LRUCache(int capacity) {
this.capacity = capacity;
tail.prev = head;
head.next = tail;
}
public Object get(Object key) {
if (!valueNodeMap.containsKey(key)) {//LRUCach未包含当前key
return null;
}
CacheNode current = valueNodeMap.get(key);
current.prev.next = current.next;
current.next.prev = current.prev;
moveToTail(current);
return valueNodeMap.get(key).value;
}
public void put(Object key, Object value) {
if (null != get(key)) {//LRUCach包含直接更新值:更新也会计入一次访问
valueNodeMap.get(key).value = value;
return;
}
if (valueNodeMap.size() == capacity) {//LRUCach未包含当前key,且容量到达capacity峰值,删除最前面的
valueNodeMap.remove(head.next.key);
head.next = head.next.next;
head.next.prev = head;
}
CacheNode insert = new CacheNode(key, value);
valueNodeMap.put(key, insert);
moveToTail(insert);
}
private void moveToTail(CacheNode current) {//移动到LRUCach尾部
current.prev = tail.prev;//current前节点指向dummy尾节点的前一个,tail.prev表示LRUCach的最后一个
tail.prev = current;//dummy尾节点前节点指向current
current.prev.next = current;//current前节点,原dummy尾节点的前一个的next指向current
current.next = tail;//current.next指向dummy尾节点
}
@Override
public String toString() {
//hashmap遍历,元素顺序会乱掉
StringBuffer sb = new StringBuffer("LRUCache[");
for (Map.Entry<Object, CacheNode> entry : valueNodeMap.entrySet()) {
sb.append("{key = " + entry.getKey() + ", value = CacheNode_Key:" + entry.getValue().key + "CacheNode_Value:" + entry.getValue().value + "},");
}
return sb.substring(0, sb.length() - 1) + "]";
}
public static void main(String[] args) {
LRUCache cache = new LRUCache(4);
cache.put("aaa", "111");
cache.put("bbb", "222");
cache.put("ccc", "333");
cache.put("ddd", "444");
cache.put("eee", "555");
cache.put("aaa", "555");
System.out.println(cache);
}
}