帮我用JAVA写一个LRU页面置换,实际代码
时间: 2023-06-10 11:03:34 浏览: 89
LRU页面置换算法(Java)
众所周知,机器学习AI助手并不是程序员,它不能直接帮你编写代码,但我可以为你提供示例代码:
```java
import java.util.HashMap;
public class LRUCache<K, V> {
private final int capacity;
private final HashMap<K, Node> map;
private Node head;
private Node tail;
//定义一个节点类
class Node {
Node prev;
Node next;
K key;
V value;
Node(K k, V v) {
this.key = k;
this.value = v;
}
}
//初始化LRU缓存
public LRUCache(int capacity) {
this.capacity = capacity;
map = new HashMap<>(capacity);
}
//获取缓存数据
public V get(K key) {
Node node = map.get(key);
if (node == null) {
return null;
}
moveToFront(node);
return node.value;
}
//将新数据插入LRU缓存
public void put(K key, V value) {
Node node = map.get(key);
if (node == null) {
if (map.size() == capacity) {
map.remove(tail.key);
removeTail();
}
node = new Node(key, value);
addToHead(node);
map.put(key, node);
} else {
node.value = value;
moveToFront(node);
}
}
//将节点移动到LRU缓存头部
private void moveToFront(Node node) {
if (node != head) {
removeNode(node);
addToHead(node);
}
}
//将节点从链表中删除
private void removeNode(Node node) {
Node prev = node.prev;
Node next = node.next;
prev.next = next;
next.prev = prev;
}
//将节点插入LRU缓存头部
private void addToHead(Node node) {
node.prev = null;
node.next = head;
if (head != null) {
head.prev = node;
}
head = node;
if (tail == null) {
tail = head;
}
}
//将节点从链表尾部删除
private void removeTail() {
if (tail != null) {
tail = tail.prev;
if (tail == null) {
head = null;
} else {
tail.next = null;
}
}
}
}
```
以上代码实现了一个简单的LRU缓存,其中封装了元素的key和value信息,使用双向链表实现了存储和访问元素的先后关系。若缓存大小超出了给定的容量,便将最久未被使用的缓存元素从缓存中删除,使得能够维护容量不变的高效存储和查找。希望对你有所帮助!
阅读全文