LRU(最近最少使用)缓存是一种数据结构,它存储最近最少使用的元素,并在缓存已满时淘汰最旧的元素。使用泛型可以让你创建可存储任何类型对象的 LRU 缓存。
实现
以下是如何在 Java 中使用泛型实现 LRU 缓存:
import java.util.HashMap;
import java.util.Map;
public class LRUCache<K, V> {
private final int capacity;
private final Map<K, Node<K, V>> cache;
private Node<K, V> head;
private Node<K, V> tail;
public LRUCache(int capacity) {
this.capacity = capacity;
this.cache = new HashMap<>();
}
public V get(K key) {
Node<K, V> node = cache.get(key);
if (node == null) {
return null;
}
moveToHead(node);
return node.value;
}
public void put(K key, V value) {
Node<K, V> node = cache.get(key);
if (node != null) {
node.value = value;
moveToHead(node);
return;
}
node = new Node<>(key, value);
cache.put(key, node);
addToHead(node);
if (cache.size() > capacity) {
removeTail();
}
}
private void moveToHead(Node<K, V> node) {
if (node == head) {
return;
}
if (node == tail) {
tail = tail.prev;
tail.next = null;
} else {
node.prev.next = node.next;
node.next.prev = node.prev;
}
node.next = head;
node.prev = null;
head = node;
}
private void addToHead(Node<K, V> node) {
if (head == null) {
head = tail = node;
return;
}
node.next = head;
head.prev = node;
head = node;
}
private void removeTail() {
if (tail == null) {
return;
}
cache.remove(tail.key);
if (tail == head) {
head = tail = null;
return;
}
tail = tail.prev;
tail.next = null;
}
private static class Node<K, V> {
K key;
V value;
Node<K, V> prev;
Node<K, V> next;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
}
}
用法
以下是如何使用此 LRU 缓存:
LRUCache<String, Integer> cache = new LRUCache<>(3);
cache.put("key1", 1);
cache.put("key2", 2);
cache.put("key3", 3);
System.out.println(cache.get("key1")); // 输出:1
cache.put("key4", 4);
System.out.println(cache.get("key2")); // 输出:null
结论
使用泛型可以让你创建可存储任何类型对象的 LRU 缓存。这使得缓存更灵活,可以用于各种场景。