生成lru算法Java代码
时间: 2023-04-04 09:05:02 浏览: 110
JAVA实现FIFO、LRU、OPT页面置换算法,有界面
5星 · 资源好评率100%
好的,我可以回答这个问题。以下是一个简单的 LRU 算法的 Java 代码实现:
```
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;
cache = new HashMap<>(capacity);
}
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 = new Node<>(key, value);
cache.put(key, node);
addToHead(node);
if (cache.size() > capacity) {
removeTail();
}
} else {
node.value = value;
moveToHead(node);
}
}
private void addToHead(Node<K, V> node) {
if (head == null) {
head = node;
tail = node;
} else {
node.next = head;
head.prev = node;
head = node;
}
}
private void removeNode(Node<K, V> node) {
if (node == head) {
head = node.next;
} else if (node == tail) {
tail = node.prev;
} else {
node.prev.next = node.next;
node.next.prev = node.prev;
}
}
private void moveToHead(Node<K, V> node) {
removeNode(node);
addToHead(node);
}
private void removeTail() {
cache.remove(tail.key);
if (tail == head) {
tail = null;
head = null;
} else {
tail = tail.prev;
tail.next = null;
}
}
private static class Node<K, V> {
private final K key;
private V value;
private Node<K, V> prev;
private Node<K, V> next;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
}
}
```
这个类实现了一个 LRU 缓存,使用双向链表和哈希表来实现。它有两个主要的方法:`get` 和 `put`。`get` 方法根据给定的键返回缓存中对应的值,如果缓存中没有该键,则返回 null。`put` 方法将给定的键值对添加到缓存中,如果缓存已满,则删除最近最少使用的键值对。
阅读全文