哈哈哈哈直接贴代码啦,代码比较简单。
参考小灰漫画。
package Lru;
import java.util.HashMap;
import java.util.Map;
public class LRUCache{
class Node{
private Node pre;
private Node next;
private String key;
private String value;
public Node(String key,String value){
this.key = key;
this.value = value;
}
}
Node head;
Node tail;
//缓存的上限
private int limit;
private Map<String,Node> hashMap;
public LRUCache(int limit){
this.limit = limit;
hashMap = new HashMap<>();
}
public void put(String key,String value){
Node node = hashMap.get(key);
if (node == null){//如果节点不存在
if(hashMap.size() >= limit){
String oldKey = removeNode(head);
hashMap.remove(oldKey);
}
node = new Node(key,value);
addNode(node);
hashMap.put(key,node);
}else{//存在的话
node.value = value;
refersh(node);
}
}
public String get(String key){
Node node = hashMap.get(key);
if (node == null){
return null;
}
refersh(node);
return node.value;
}
public void remove(String key){
Node node = hashMap.get(key);
removeNode(node);
hashMap.remove(key);
}
//针对Node的refersh
public void refersh(Node node){
if(tail == node){
return;
}
removeNode(node);
addNode(node);
}
//针对Node的add
public void addNode(Node node){
if(tail != null){
tail.next = node;
node.pre = tail;
tail = node;
}
if(head == null){
head = node;
tail = node;
}
}
//针对Node的remove
public String removeNode(Node node){
//删除尾节点
if(tail == node){
tail = tail.pre;
}else if(node == head){//删除头结点
head = head.next;
}else{//中间节点
node.pre.next = node.next;
node.next.pre = node.pre;
}
return node.key;
}
public static void main(String[] args) {
LRUCache lruCache = new LRUCache(5);
lruCache.put("001", "用户1信息");
lruCache.put("002", "用户1信息");
lruCache.put("003", "用户1信息");
lruCache.put("004", "用户1信息");
lruCache.put("005", "用户1信息");
lruCache.get("002");
lruCache.put("004", "用户2信息更新");
lruCache.put("006", "用户6信息");
System.out.println(lruCache.get("001"));
System.out.println(lruCache.get("006"));
}
}
这个博客介绍了一个简单的LRU(最近最少使用)缓存淘汰算法的Java实现。通过使用双向链表结合哈希映射,当缓存满时,会根据访问顺序移除最不常使用的条目。博客中展示了如何插入、获取、更新和删除缓存项,并给出了一个包含插入、更新和查询操作的示例。
171万+

被折叠的 条评论
为什么被折叠?



