Java使用双向链表 和哈希表 实现LRU缓存
-
getValue(Integer key) :获取键对应的值,并标记最近使用过。 -
setKeyValue(Integer key, String value) :将键值对插入到缓存,如果存在则删除旧的值。 -
removeKey(Integer key) :将键值对从缓存中移除。
public class LRUCache {
private Integer maxCacheSize;
private Map<Integer, DoubleListNode> map;
private DoubleListNode head;
private DoubleListNode tail;
public LRUCache(Integer maxCacheSize) {
this.maxCacheSize = maxCacheSize;
this.map = new HashMap<>();
}
public String getValue(Integer key) {
DoubleListNode node = map.get(key);
if (node == null) {
return null;
}
if (node != head) {
removeFromLinkedList(node);
insertAtFrontOfLinkedList(node);
}
return node.value;
}
public void setKeyValue(Integer key, String value) {
removeKey(key);
if (map.size() >= maxCacheSize && tail != null) {
removeKey(tail.key);
}
DoubleListNode node = new DoubleListNode(key, value);
insertAtFrontOfLinkedList(node);
map.put(key, node);
}
public void removeKey(Integer key) {
DoubleListNode node = map.get(key);
removeFromLinkedList(node);
map.remove(key);
}
private void removeFromLinkedList(DoubleListNode node) {
if (node == null) {
return;
}
if (node.pre != null) {
node.pre.next = node.next;
}
if (node.next != null) {
node.next.pre = node.pre;
}
if (node == tail) {
tail = node.pre;
}
if (node == head) {
head = node.next;
}
}
private void insertAtFrontOfLinkedList(DoubleListNode node) {
node.pre = node.next = null;
if (head == null) {
head = node;
tail = node;
} else {
head.pre = node;
node.next = head;
head = node;
}
}
static class DoubleListNode {
private Integer key;
private String value;
private DoubleListNode next, pre;
public DoubleListNode(Integer key, String value) {
this.key = key;
this.value = value;
}
}
}
|